运行“源”来自蟒蛇

发布于 2024-09-06 01:26:44 字数 484 浏览 8 评论 0原文

我有一个文件 a.txt ,其中包含我想要运行的命令行,例如:

echo 1
echo 2
echo 3

如果我使用 csh (unix),我会执行 source a.txt 并且它会运行。 我想从 python 中运行 os.execl ,但是我得到:

>>> os.execl("source", "a.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/os.py", line 322, in execl
    execv(file, args)
OSError: [Errno 2] No such file or directory

如何做到这一点?

I have a file a.txt with lines of commands I want to run, say:

echo 1
echo 2
echo 3

If I was on csh (unix), I would have done source a.txt and it would run.
From python I want to run os.execl with it, however I get:

>>> os.execl("source", "a.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/os.py", line 322, in execl
    execv(file, args)
OSError: [Errno 2] No such file or directory

How to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

世态炎凉 2024-09-13 01:26:44

source 不是可执行程序,因此不能直接执行它。相反,它是 shell 中的内置命令。如果您确实需要访问该 shell,则需要启动该 shell。但如果您只想运行脚本,则根本不需要使用源代码 - 只需让 shell 直接执行脚本即可:

os.execl("/bin/bash", "a.txt")

source is not an executable program, so you can't execute it directly. Rather, it is a builtin command in the shell. You would need to launch that shell instead if you really needed access to it. But if you just want to run the script, you don't need to use source at all – just have the shell execute your script directly:

os.execl("/bin/bash", "a.txt")
┾廆蒐ゝ 2024-09-13 01:26:44

您没有提供 source 的完整路径,并且 os.execl 需要该路径。

如果您想使用PATH环境变量,则应该使用os.execlp

请参阅os 模块文档

尽管,正如 @Walter 提到的,您可能需要 /bin/bash 而不是 source

os.execl("/bin/bash", "a.txt")

You are not supplying the full path to source, and os.execl needs the path.

If you want to use the PATH env variable, you should use os.execlp.

See the os module documentation.

Although, as @Walter mentions, you probably want /bin/bash instead of source:

os.execl("/bin/bash", "a.txt")
昔日梦未散 2024-09-13 01:26:44

您只想运行脚本吗?在这种情况下,您可以将“source”替换为“bash”,并且可能会得到您想要的。

如果您希望正在获取的东西对 Python 进程产生副作用,例如设置环境变量或其他东西,那么您可能不走运。

Do you just want to run a script? In that case, you can replace "source" with "bash" and probably get what you want.

If you want the thing-being-sourced to have side-effects on the Python process, like setting environment variables or something, you are probably out of luck.

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