我正在尝试使用 Python 的 Popen 来更改我的工作目录并执行命令。
pg = subprocess.Popen("cd c:/mydirectory ; ./runExecutable.exe --help", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
buff,buffErr = pg.communicate()
但是,powershell 返回“系统找不到指定的路径”。路径does exist.
If I run
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,但我想知道为什么会发生这种情况。
UPDATE :
我已经测试过将路径传递给 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!