运行“源”来自蟒蛇
我有一个文件 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
source
不是可执行程序,因此不能直接执行它。相反,它是 shell 中的内置命令。如果您确实需要访问该 shell,则需要启动该 shell。但如果您只想运行脚本,则根本不需要使用源代码 - 只需让 shell 直接执行脚本即可: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:您没有提供
source
的完整路径,并且os.execl
需要该路径。如果您想使用
PATH
环境变量,则应该使用os.execlp
。请参阅os 模块文档。
尽管,正如 @Walter 提到的,您可能需要
/bin/bash
而不是source
:You are not supplying the full path to
source
, andos.execl
needs the path.If you want to use the
PATH
env variable, you should useos.execlp
.See the os module documentation.
Although, as @Walter mentions, you probably want
/bin/bash
instead ofsource
:您只想运行脚本吗?在这种情况下,您可以将“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.