sh script equivalent of python script
Ok, so I have the following situation. I need to edit the PYTHONPATH dynamically on a target PC. Now the structure of the project is:
trunk
bi开发者_高级运维n
start_script
dependencies
dependencies
From python I could do, from start_script:
root_path = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]
dependencies_root = os.path.join(root_path, 'dependencies')
from sys import path
path.extend([root_path, dependencies_root])
This would do the trick but I need to start new python processes with process.Popen and the changes to sys.path are gone by then it seems.
Now I was thinking a sh script would do the job better here, unfortunately I'm a total noob here and have no idea how to proceed. The sh script should do basically the things the python from above did, so:
[1] Get the absolute path of the directory the script is located
[2] Get the parent of that folder (say parent_path)
[3] export PYTHONPATH=$PYTHONPATH:parent_path
[4] python start_script.py
So basically the first two steps are the ones I need help with. Also if there is a way to make changes to python's sys.path persist on a subprocess opened with subprocess.Popen please let me know.
You could just update the PYTHONPATH
environment variable at the same moment you update sys.path
in start_script, using the os.environ
dict.
I would use a .pth
file. See http://docs.python.org/install/index.html#inst-search-path
A .pth
file is a file consisting in one directory path per line. It will insert the listed directories into your python path.
That may be better than executing shell scripts, with all its downsides (more complex installation, break portability, etc.)
Why not use the env
argument of subprocess.Popen?
class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of inheriting the current process’ environment, which is the default behavior.
Or if you just want to start a python process you could simply use the multiprocessing module.
Example from docs:
from multiprocessing import Process
def f(name):
print 'hello', name
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
精彩评论