简体   繁体   中英

Python and the environment

I have a file ( myenv.sh ) with the following content

export MYVAR="HELLO"

And then I have my program ( myhugeprogram.py ):

#!/usr/bin/env python
import os
print os.environ['MYVAR']

Which is executable: chmod 755 myhugeprogram.py

Now I source my environment: source myenv.sh

And run my program:

./myhugeprogram.py
HELLO

As expected. Now I run it non-interactively via SSH:

user1@host1:~$ ssh user2@host2 ./myhugeprogram.py
Traceback (most recent call last):
  File "./myhugeprogram.py", line 3, in <module>
    print os.environ['MYVAR']
  File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__
    raise KeyError(key)
KeyError: 'MYVAR'

Which is normal, because I have not sourced myenv.sh . Now the question:

How do I source a Bash file which sets some environment variables before executing my Python script when running non-interactivaly via SSH?

Two ways I can think of:

  • include the source command in the ssh command you run, for example

    ssh user2@host2 "source myenv.sh; ./myhugeprogram.py"
  • set the environment variable in your .bashrc file.

Write a shell script wrapper (visible from both environments) that sets the environment and calls the program along with all arguments together. You could make this shell script intelligent so that it only sets the environment based on the current environment, so you only ever have to call that wrapper script regardless of your context and can treat it like a black box.

you should export/source the variable in your script itself,

since if you open a session of SSH and fire source command, then use another session for execution of the script,

the environment variable will not be available as the whole new environment will be loaded again.

you can set the environment variable for your script using os.environ["ASD"] = "asd" syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM