How to add the current dir to sys.path when calling a python file?

P

Peng Yu

Hi,

man python says "If a script argument is given, the directory
containing the script is inserted in the path in front of $PYTHONPATH.
The search path can be manipulated from within a Python program as
the variable sys.path." Instead I want to have the current directory
inserted to the front of $PYTHONPATH without changing anything the
script. Is there a way to do so?
 
S

Steven D'Aprano

Hi,

man python says "If a script argument is given, the directory
containing the script is inserted in the path in front of $PYTHONPATH.
The search path can be manipulated from within a Python program as the
variable sys.path." Instead I want to have the current directory
inserted to the front of $PYTHONPATH without changing anything the
script. Is there a way to do so?

No. If you want to manipulate the path, you have to write code to do so,
and put it in your script. That's very simple:

import os, sys
sys.path.insert(0, os.getcwd())
 
R

rusi

Hi,

man python says "If a script  argument  is  given,  the directory
containing the script is inserted in the path in front of $PYTHONPATH.
The search path can be manipulated from  within a Python program as
the variable sys.path." Instead I want to have the current directory
inserted to the front of $PYTHONPATH without changing anything the
script. Is there a way to do so?

Have you seen http://docs.python.org/2/library/site.html ?
 
P

Peng Yu

No. If you want to manipulate the path, you have to write code to do so,
and put it in your script. That's very simple:

import os, sys
sys.path.insert(0, os.getcwd())

Actually, it is quite simple. Just use stdin to take the python file.

~/linux/test/python/man/library/sys/path$ cat.sh main.py subdir/main.py
==> main.py <==
#!/usr/bin/env python

import sys

print sys.path

==> subdir/main.py <==
#!/usr/bin/env python

import sys

print sys.path
~/linux/test/python/man/library/sys/path$ diff <(python - < main.py)
<(python - < subdir/main.py)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top