python脚本的问题

发布于 2024-09-05 11:29:54 字数 249 浏览 2 评论 0原文

我想从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沙沙粒小 2024-09-12 11:29:54

子进程不能影响父进程的环境。您能做的最好的事情就是在单独的进程中运行 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

御弟哥哥 2024-09-12 11:29:54

您可以这样拼凑它:

#!/usr/bin/env python
# This is kludge.py

print "setenv VARNAME \"the value\""

在您的情况下,您可以让 file.sh 打印 setenv 行。

然后来自 csh:

$ eval `./kludge.py`
$ echo $VARNAME 
the value

这并不干净,但这是让子进程影响其父进程环境的唯一方法。这只是因为父进程通过 eval 显式地让它发生。

You can kludge it this way:

#!/usr/bin/env python
# This is kludge.py

print "setenv VARNAME \"the value\""

In your case, you can have the file.sh print the setenv line.

Then from csh:

$ eval `./kludge.py`
$ echo $VARNAME 
the value

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文