1

Here is my file structure:

-test --m1 ---t.py --m2 ---__init__.py ---utils.py 

t.py:

from m2.utils import * print foo() 

utils.py:

def foo(): return 5 

__init__.py is empty

It works in my local environment (macOS Sierra python 2.7.10):

Shangtong@Shangtong:~/GitHub/PaperReplication/test$ python m1/t.py 5 Shangtong@Shangtong:~/GitHub/PaperReplication/test$ echo $PYTHONPATH :/Users/Shangtong/DevelopmentKits/libsvm-3.20/python 

However it doesn't work in my server (Python 2.7.8):

[shangton@jasper test]$ python m1/t.py Traceback (most recent call last): File "m1/t.py", line 1, in <module> from m2.utils import * ImportError: No module named m2.utils [shangton@jasper test]$ ls -al total 16 drwxrwxr-x 4 shangton shangton 4096 Jan 28 09:10 . drwx------ 4 shangton shangton 4096 Jan 28 10:09 .. drwxrwxr-x 2 shangton shangton 4096 Jan 28 09:12 m1 drwxrwxr-x 2 shangton shangton 4096 Jan 28 10:09 m2 [shangton@jasper test]$ echo $PYTHONPATH /global/software/python/Python-2.7.8/lib/python2.7/site-packages/:/global/software/python/Python-2.7.3/lib/python2.7/site-packages/:~/PaperReplication/:~/test/m2:~/test 
4
  • If you had a m1/__init__.py, you could run python -m m1.t Commented Jan 28, 2017 at 17:26
  • 2
    ...or if you set PYTHONPATH=$PWD, then this should work immediately as you intend. Commented Jan 28, 2017 at 17:26
  • 1
    ~ isn't guaranteed to expand -- use $HOME, not ~, when setting environment variables. Python may do it manually -- there's a library function for the purpose -- but many programs won't. Commented Jan 28, 2017 at 17:27
  • @CharlesDuffy It works! Thanks Commented Jan 28, 2017 at 17:28

1 Answer 1

2

You're demonstrating that your PYTHONPATH contains:

~/test/m2:~/test 

However, ~ is not actually a valid PATH component! It's a hint to your shell to replace that character with your home directory (when unquoted, in the first position in a word, and otherwise where other conditions are met) -- but Python is not your shell, and if your shell didn't honor that hint when you were setting the environment variable (perhaps because, being in the middle of a string, it wasn't in leading position), it won't be honored later unless Python explicitly calls os.path.expanduser().

When setting an environment variable, use $HOME:

PYTHONPATH=$HOME/test 
Sign up to request clarification or add additional context in comments.

2 Comments

It works.Thanks! Could you please explain one more thing: why does it work in my local environment?
In your local environment, there's no ~ in your PYTHONPATH.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.