【发布时间】:2017-12-18 19:48:08
【问题描述】:
我正在尝试使用 Python 的 Popen 更改我的工作目录并执行命令。
pg = subprocess.Popen("cd c:/mydirectory ; ./runExecutable.exe --help", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
buff,buffErr = pg.communicate()
但是,powershell 返回“系统找不到指定的路径”。路径确实存在。
如果我跑步
pg = subprocess.Popen("cd c:/mydirectory ;", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
它返回相同的东西。
但是,如果我运行这个:(不带分号)
pg = subprocess.Popen("cd c:/mydirectory",stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
命令返回没有错误。这使我相信分号是问题。这种行为的原因是什么?我该如何解决?
我知道我只能执行 c:/mydirectory/runExecutable.exe --help,但我想知道为什么会这样。
更新:
我已经测试了将路径传递给 powershell 作为 Popen 的 executable 参数的参数。仅powershell.exe 可能还不够。要查找powershell 的真正绝对路径,请执行where.exe powershell。然后你可以将它传递给 Popen。请注意,shell 仍然正确。它将使用默认shell,但将命令传递给powershell.exe
powershell = C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
pg = subprocess.Popen("cd c:/mydirectory ; ./runExecutable.exe", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, executable=powershell)
buff,buffErr = pg.communicate()
//It works!
【问题讨论】:
标签: python powershell subprocess popen