【问题标题】:Python subprocess.call raise OSError with linux source command [duplicate]Python subprocess.call 使用 linux 源命令引发 OSError [重复]
【发布时间】:2019-07-22 00:25:12
【问题描述】:

在 python2.7 中,我们可以使用 subprocess 包执行外部 linux 命令。

import subprocess   
subprocess.call(["ls", "-l"]) // or  
subprocess.call("ls -l".split())

两者都有效。我在当前工作目录中有一个文件 test.sh,其中仅包含

date

所以我尝试了

>>> subprocess.call("pwd".split())
/home/ckim
0
>>> subprocess.call("cat test.sh".split())
date
0
>>> subprocess.call("source test.sh".split())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 523, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

怎么了?
ADD(ANSWER):这个问题和答案有足够的信息(但我会在这里留下我的问题..)Calling the "source" command from subprocess.Popen

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    source is a shell builtin command。 Python 的 subprocess module 用于生成新进程,而不是运行适当的 Bourne shell(或 zsh 或 ksh 等)。您无法从 subprocess.call 访问 Shel 内置函数。

    要确定您是否可以使用subprocess 模块运行特定命令,您可能需要使用which 来获取有关您需要使用的命令的信息:

    user@machine: ~
    $ which source                                                                                                                                  [7:41:38]
    source: shell built-in command
    
    user@machine: ~
    $ which cat                                                                                                                                     [7:41:42]
    /bin/cat
    
    user@machine: ~
    $ which ls                                                                                                                                      [7:41:47]
    ls: aliased to ls --color=tty
    

    【讨论】:

    • 哦,原来如此。谢谢! (所以我应该使用 execfile() 函数)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    相关资源
    最近更新 更多