0

我正在尝试使用 Popen 运行“RepoInitCmd”,如下所示并遇到以下错误..可以提供有关错误的输入吗?

import subprocess
Branch_Name='ab_mr2'
RepoInitCmd =  'repo init -u git://git.company.com/platform/manifest.git -b ' + Branch_Name
proc = subprocess.Popen([RepoInitCmd], stderr=subprocess.PIPE)
out, error = proc.communicate()

错误:-

  File "test.py", line 4, in <module>
    proc = subprocess.Popen([RepoInitCmd], stderr=subprocess.PIPE)
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
4

2 回答 2

1
proc = subprocess.Popen(RepoInitCmd.split(" "), stderr=subprocess.PIPE)

或者

import shlex
proc = subprocess.Popen(shlex.split(RepoInitCmd), stderr=subprocess.PIPE)

您需要传递一组参数。第一个参数被视为二进制名称,因此“repo init ...”是它要查找的程序的名称。你需要通过类似的东西["repo", "init", ...]

于 2013-07-01T04:08:05.260 回答
0

默认情况下,Popen 期望命令行作为列表传递。特别是,将运行的实际命令(在本例中为“repo”)应该是列表的第一项。与其将命令编写为字符串并使用 split 或 shlex 将它们作为列表传递给 Popen,我更喜欢从一开始就将命令行作为列表进行管理,因为这样可以更容易地在代码中构建命令行。所以,在这种情况下,我可能会写这样的东西:

RepoInitCmd = ['repo', 'init', '-u', 'git://git.company.com/platform/manifest.git']
RepoInitCmd.extend(['-b', Branch_Name])
proc = subprocess.Popen(RepoInitCmd, stderr=subprocess.PIPE)

请注意,如果您想要或需要将命令行作为单个字符串传递(可能是为了利用 shell 功能),那么如果您不介意运行额外的 shell 进程的额外开销,则可以启用 shell 模式:

proc  = subprocess.Popen(RepoInitCmd, shell=True, stderr=subprocess.PIPE)
于 2013-07-01T06:16:38.577 回答