python脚本的问题
我想从 python 脚本运行 csh 文件,
例如,
#!/usr/bin/python
import os
os.system("source path/to/file.csh")
并且我希望该文件在运行 python 脚本的同一个 shell 中运行,因为 file.csh
脚本设置了一些环境我需要的变量。
有谁知道如何在Python中做到这一点?
I want to run a csh file from a python script,
example,
#!/usr/bin/python
import os
os.system("source path/to/file.csh")
and I want this file to run in the same shell as I am running the python script, because the file.csh
script is settings some environment variables that I need.
Does anyone know how to do this in Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
子进程不能影响父进程的环境。您能做的最好的事情就是在单独的进程中运行 csh 脚本,获取它定义的环境变量,然后在 python 脚本中设置每个环境变量。
即使这样,python 脚本也无法影响运行 python 脚本的 shell。
解决此问题的常见方法(据我所知)是让脚本发出 shell 命令来设置环境,然后从主 shell 运行脚本并评估返回的结果。
有关更多信息,您可能想查看此问题:shell 脚本可以设置调用 shell 的环境变量
A child process cannot affect the environment of the parent process. The best you can do is to run your csh script in a separate process, get the environment variables that it defines, then set each environment variable in your python script.
Even with that, the python script won't be able to affect the shell in which you run the python script.
The common way to solve this (AFAIK) is to have your script emit shell commands to set the environment, then from the main shell you run the script and eval what you get back.
For more information you might want to check out this question: can a shell script set environment variables of the calling shell
您可以这样拼凑它:
在您的情况下,您可以让 file.sh 打印
setenv
行。然后来自 csh:
这并不干净,但这是让子进程影响其父进程环境的唯一方法。这只是因为父进程通过
eval
显式地让它发生。You can kludge it this way:
In your case, you can have the file.sh print the
setenv
line.Then from csh:
This isn't clean, but it is the only way to have a child process effect the environment of its parent. This is only because the parent process is explicitly letting it happen with
eval
.