我们可以将python脚本修改的环境变量传递给外壳吗?
对于以下 python 脚本:
import os
os.system('PYTHONPATH=\user\...')
os.system('export PYTHONPATH')
....
执行此脚本后,我们是否可以将 PYTHONPATH
变量“导出”到 shell?
For the following python script:
import os
os.system('PYTHONPATH=\user\...')
os.system('export PYTHONPATH')
....
Is there anyway we can "export" the PYTHONPATH
variable to the shell after executing this script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这是不可能的。当Python进程启动时,它会获得自己的环境副本,从父shell复制。 Python进程只能修改私有副本,并且更改不会传播回父进程。
如果你想做这样的事情,你能得到的最好的方法是打印执行所需的环境变量更改所需的 shell 命令,例如
并使用运行脚本
No, this is not possible. When the Python process is launched, it gets its own copy of the environment, copied from the parent shell. The Python process can only modify the private copy, and changes are not propagated back to the parent process.
If you want to do something like this, the best you can get is to print the shell commands needed to do the desired environment variable changes, e.g.
and run the script using
斯文的回答很好。
另一种可能的方法是从 Python 脚本调用新的 shell 进程,具体取决于您的要求。由于新 shell 是 Python 进程的子进程,因此它将继承所有环境变量。
显然这并不总是您想要做的,但它是一种替代方案。
Sven's answer is a good one.
Another possible approach, depending on your requirements, is to invoke a new shell process from the Python script. Since the new shell is a child of the Python process, it will inherit any environment variables.
Obviously this isn't always what you want to do, but it's an alternative.