2017-04-25 55 views
0

新的python,我发现子进程的check_output在Windows上很好地运行,但它似乎只运行Windows PATH环境变量中的cmds。任何方式来在python子进程中使用绝对路径check_output

我可以执行以下罚款:显示

import sys 
from subprocess import check_output 

cmd = check_output("ipconfig", shell=True) 
print(cmd.decode(sys.stdout.encoding)) 

和ipconfig输出细。

如果我尝试运行不在路径中的特定命令并尝试绝对路径,我会收到错误。

import sys 
from subprocess import check_output 

cmd = check_output("c:\\test\\test.exe", shell=True) 
print(cmd.decode(sys.stdout.encoding)) 

有没有办法使用绝对路径引用check_output?我是没有发现任何..

我甚至试图改变该目录..

import sys 
from subprocess import check_output 
import os 

os.chdir("c:\\test\\") 
cmd = check_output("test.exe", shell=True) 
print(cmd.decode(sys.stdout.encoding)) 

,但我得到以下错误

File "C:\Python35\lib\subprocess.py", line 398, in run 
    output=stdout, stderr=stderr) 
subprocess.CalledProcessError: Command 'naviseccli.exe' returned non-zero exit status 1 

Process finished with exit code 1 
+1

显然,你成功地执行'naviseccli.exe'就好了,但它以非零退出状态返回,这会导致'CalledProcessError'(这是['check_output']的预期行为(https://docs.python.org/3/library/subprocess.html#subprocess.check_output) )。 – mkrieger1

+0

当你执行'check_output(“c:\\ test \\ test.exe”,shell = True)时,你会得到什么错误? – mkrieger1

回答

1

Popen提供了 'CWD' 的说法,这将在定义的目录下执行:

import subprocess 
cmd = subprocess.Popen('test.exe', stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd='C:/test', shell=True) 

out, err = cmd.communicate() 
print (out) 

使用check_output:

subprocess.check_output('cd C:/windows && notepad.exe', shell=True) 
+0

完美! thx,这让我想要什么。我从.Net转移到python,所以它是2 LOL之间的一个差异世界 –

1

请阅读有关的CalledProcessError文档。

您可以通过在try ... except块中捕获此异常并使用异常实例的output属性来检查输出。

try: 
    ... ...      # Running the command. 
except CalledProcessError as cmderr: 
    print (cmderr.output)   # Example of using the output. 

通过这种方式,您可以检查失败的命令的退出状态和输出。我不知道是什么触发了确切的错误,但这不可能是使用绝对路径的结果。

相关问题