简体   繁体   English

Python及环境

[英]Python and the environment

I have a file ( myenv.sh ) with the following content我有一个包含以下内容的文件 ( myenv.sh )

export MYVAR="HELLO"

And then I have my program ( myhugeprogram.py ):然后我有我的程序( myhugeprogram.py ):

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

Which is executable: chmod 755 myhugeprogram.py哪个是可执行文件: chmod 755 myhugeprogram.py

Now I source my environment: source myenv.sh现在我获取我的环境: source myenv.sh

And run my program:并运行我的程序:

./myhugeprogram.py
HELLO

As expected.不出所料。 Now I run it non-interactively via SSH:现在我通过 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 .这很正常,因为我没有获取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?当通过 SSH 非交互运行时,如何在执行我的 Python 脚本之前设置一些环境变量的 Bash 文件?

Two ways I can think of:我能想到的两种方法:

  • include the source command in the ssh command you run, for example例如,在您运行的 ssh 命令中包含 source 命令

    ssh user2@host2 "source myenv.sh; ./myhugeprogram.py"
  • set the environment variable in your .bashrc file..bashrc文件中设置环境变量。

Write a shell script wrapper (visible from both environments) that sets the environment and calls the program along with all arguments together.编写一个 shell 脚本包装器(在两个环境中都可见),它设置环境并将程序与所有 arguments 一起调用。 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.您可以使这个 shell 脚本智能化,以便它仅根据当前环境设置环境,因此无论您的上下文如何,您都只需调用该包装器脚本,并且可以将其视为黑盒。

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,因为如果你打开 SSH 的 session 和火源命令,然后使用另一个 session 来执行脚本,

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.您可以使用os.environ["ASD"] = "asd"语法为您的脚本设置环境变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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