在 python 子进程 check_output 中使用绝对路径的任何方法

joh*_*son 6 python

对于 python 来说,我发现子进程的 check_output 在 Windows 上运行得很好,但它似乎只运行 Windows PATH 环境变量中的 cmd。

我可以执行以下命令:

import sys
from subprocess import check_output

cmd = check_output("ipconfig", shell=True)
print(cmd.decode(sys.stdout.encoding))
Run Code Online (Sandbox Code Playgroud)

并且 ipconfig 输出显示正常。

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

import sys
from subprocess import check_output

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

是否无法对 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))
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误

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
Run Code Online (Sandbox Code Playgroud)

Mau*_*yer 5

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)
Run Code Online (Sandbox Code Playgroud)

使用 check_output:

subprocess.check_output('cd C:/windows && notepad.exe', shell=True)
Run Code Online (Sandbox Code Playgroud)