简体   繁体   English

Python 和环境变量不起作用

[英]Python and environment variables not working

In a Docker container on Ubuntu, I'm running a .sh file which calls python3 my_script_file.py .在 Ubuntu 上的 Docker 容器中,我正在运行一个调用python3 my_script_file.py.sh文件。 In that file, I do:在那个文件中,我这样做:

commands = []
commands.append("export OMP_NUM_THREADS=4")
commands.append("echo $OMP_NUM_THREADS")

I then execute the commands array with:然后我执行命令数组:

def execute_commands_list(commands, no_bash_script = False):
    for command in commands:
        if not no_bash_script and gc.output_to_bash_script:
            write_command_to_bash_script(command)
        else:
            print("     [  " + command + "  ]")

            ret = subprocess.call(command, shell=True, executable="/bin/bash")

            assert ret==0 or ret==2, "bash return code error: " + str(ret) + " " + command

Here is the output:这是输出:

     [  export OMP_NUM_THREADS=4  ]
     [  echo $OMP_NUM_THREADS  ]


(that's a blank line). (这是一个空行)。 I try running echo $OMP_NUM_THREADS in the terminal after execution myself, and get nothing.我自己执行后尝试在终端中运行 echo $OMP_NUM_THREADS ,但一无所获。 If I run those both commands manually however the env var is set.如果我手动运行这两个命令,则会设置 env var。

(I have also tried os.environ, and that has failed as well) (我也试过 os.environ,但也失败了)

What am I missing?我错过了什么?

(For reference, the .sh file is:) (作为参考,.sh 文件是:)

#!/bin/bash -p

python3 my_script_file.py

That's probably because the scope of export is limited only to the current shell it's being running on.这可能是因为export的范围仅限于它正在运行的当前 shell。 Meaning that only the shell the subprocess ran from, this environment variable will be visible to.这意味着只有subprocess运行的 shell,这个环境变量才可见。

If you want to make this environment variable globally exposed, and given you're running from a linux machine of some sort, I'd suggest writing it to /etc/environment in the format of KEY=VALUE .如果你想让这个环境变量全局公开,并且你是从某种 Linux 机器上运行的,我建议将它以KEY=VALUE的格式写入/etc/environment

For example in your case, instead of例如在你的情况下,而不是

export OMP_NUM_THREADS=4

Replace it with:替换为:

echo OMP_NUM_THREADS=4 >> /etc/environment

Note!笔记! Since environment is located under /etc there's a good chance its permissions are set to allow write only to a sudo user, so make sure you include that in your subprocess call.由于environment位于/etc下,很有可能将其权限设置为仅允许写入 sudo 用户,因此请确保将其包含在subprocess调用中。

You can use something like the following:您可以使用以下内容:

echo 'OMP_NUM_THREADS=4' | sudo tee -a /etc/environment > /dev/null

tee prints the text to stdout, too. tee将文本打印到标准输出。 In order to mute it so it behaves more similar to shell appending ( >> ), route the stdout to /dev/null .为了使其静音,使其行为更类似于 shell 附加 ( >> ),请将 stdout 路由到/dev/null

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

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