Reputation: 44371
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?
Upvotes: 0
Views: 367
Reputation: 14854
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.
Upvotes: 0
Reputation: 46316
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.
Upvotes: 3
Reputation: 8607
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.
Upvotes: 0