如何在python脚本中修改系统路径变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4081330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:09:07  来源:igfitidea点击:

how do I modify the system path variable in python script?

pythonpathenvironment-variables

提问by Joe Schmoe

I'm trying to run a python script from cron, but its not running properly so I'm assuming its the different path env variable. Is there anyway to change the variable within a python script?

我正在尝试从 cron 运行 python 脚本,但它运行不正常,所以我假设它的路径环境变量不同。无论如何要更改python脚本中的变量?

采纳答案by unutbu

You shouldn't need to set the PATH from within the python script. Instead, put something like

您不需要在 python 脚本中设置 PATH。相反,把类似的东西

USER=joe
HOME=/home/joe
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/some/other/path
PYTHONPATH=/home/joe/pybin
MAILTO=joe
LANG=en_US.UTF-8

#min hr    day   mon dow
*/5  12    *     *   *     reminder.py 'Eat lunch'

at the top of your crontab. These environment variables will then be available to all cron jobs run through your crontab.

在你的 crontab 的顶部。然后,这些环境变量将可用于通过您的 crontab 运行的所有 cron 作业。

回答by Greg Gauthier

@ubuntu has the right approach, but for what it's worth, @Joe Schmoe, if you ever need the info:

@ubuntu 有正确的方法,但对于它的价值,@Joe Schmoe,如果您需要信息:

import sys
print sys.path
['.', '/usr/local/bin', '/usr/local/lib/python2.6/dist-packages',...]
sys.path.append('/home/JoeBlow/python_scripts')
print sys.path
['.', '/usr/local/bin', '/usr/local/lib/python2.6/dist-packages', '/home/JoeBlow/python_scripts',...]
   

sys.path is an array containing everything that was in your initiating script's PYTHONPATH variable (or whatever your shell's default PYTHONPATH is).

sys.path 是一个数组,其中包含您的启动脚本的 PYTHONPATH 变量(或您的 shell 的默认 PYTHONPATH 是什么)中的所有内容。

回答by hlongmore

While the accepted answer works for the OP's purposes, and while the second answer is correct for updating the python sys.path variable, I think, if the OP weren't able to use the accepted answer (because, say, there was a policy against modifying the OS PATH variable on build/test machines), something like this SO answerwould be what they are looking for. Summarizing the simple case here, to change the OS PATH environment variable:

虽然接受的答案适用于 OP 的目的,而第二个答案对于更新 python sys.path 变量是正确的,但我认为,如果 OP 无法使用接受的答案(因为,比如说,有一个政策反对在构建/测试机器上修改 OS PATH 变量),像这样的 SO 答案将是他们正在寻找的。总结这里的简单情况,更改 OS PATH 环境变量:

app_path = os.path.join(root_path, 'other', 'dir', 'to', 'app')
os.environ["PATH"] += os.pathsep + app_path

At least, this is what I was hoping to find when I read the question.

至少,这是我在阅读问题时希望找到的。