为什么subprocess.Popen无法工作

7
我尝试了很多事情,但出于某些原因我无法让它们工作。我正在尝试使用Python脚本运行MS VS的dumpbin实用程序。
以下是我尝试过的(但对我来说没有起作用):
1.
tempFile = open('C:\\Windows\\temp\\tempExports.txt', 'w')
command = '"C:/Program Files/Microsoft Visual Studio 8/VC/bin/dumpbin" /EXPORTS ' + dllFilePath
process = subprocess.Popen(command, stdout=tempFile)
process.wait()
tempFile.close()

2.
tempFile = open('C:\\Windows\\temp\\tempExports.txt', 'w')
command = 'C:/Program Files/Microsoft Visual Studio 8/VC/bin/dumpbin /EXPORTS ' + dllFilePath
process = subprocess.Popen(command, stdout=tempFile)
process.wait()
tempFile.close()

3.
tempFile = open('C:\\Windows\\temp\\tempExports.txt', 'w')
process = subprocess.Popen(['C:\\Program Files\\Microsoft Visual Studio 8\\VC\\bin\\dumpbin', '/EXPORTS', dllFilePath], stdout = tempFile)
process.wait()
tempFile.close()

有人知道如何在Python中正确执行我正在尝试的操作吗(dumpbin /EXPORTS C:\Windows\system32\kernel32.dll > tempfile.txt)?


1
你可能需要详细说明它为什么不起作用。你有收到任何错误信息或其他提示吗? - Thomas K
你尝试过使用'C:\\Program Files\\Microsoft Visual Studio 8\\VC\\bin\\dumpbin.exe'了吗? - rumpel
@rumpel 嗯,也没用。 - Hayri Uğur Koltuk
1
@Thomas K,好的,临时文件是空的,这就是我所说的“不起作用”的意思。 - Hayri Uğur Koltuk
2个回答

8
< p > 对于Popen的参数模式,非shell调用需要一个字符串列表,而shell调用需要一个字符串。这很容易修复。给定代码如下:

>>> command = '"C:/Program Files/Microsoft Visual Studio 8/VC/bin/dumpbin" /EXPORTS ' + dllFilePath

要么使用shell=True调用subprocess.Popen

>>> process = subprocess.Popen(command, stdout=tempFile, shell=True)

或者使用shlex.split创建参数列表:

>>> process = subprocess.Popen(shlex.split(command), stdout=tempFile)

尝试了两种方法,但都无法使其工作。顺便提一下,dllpath是:'C:\Windows\system32\user32.dll',也许有帮助... - Hayri Uğur Koltuk
2
注意:从2.7版本开始,shell=true被认为是一种安全风险。 - thundergolfer
@thundergolfer 这完全取决于你是否控制命令(就像OP的问题)或来自不受信任的外部来源:https://docs.python.org/2.7/library/subprocess.html#frequently-used-arguments - Raymond Hettinger

2
with tempFile:
    subprocess.check_call([
        r'C:\Program Files\Microsoft Visual Studio 8\VC\bin\dumpbin.exe',
        '/EXPORTS', 
        dllFilePath], stdout=tempFile)

现在我们确定它不起作用了 :) subprocess.CalledProcessError: 命令 '['C:\Program Files\Microsoft Visual Studio 8\VC\bin\dumpbin.exe', '/EXPORTS', 'C:\Windows\system32\user32.dll']' 返回非零退出状态 -1073741515 - Hayri Uğur Koltuk
当我执行以下代码时: subprocess.check_call('"C:\Program Files\Microsoft Visual Studio 8\VC\bin\dumpbin.exe" /EXPORTS ' + dllFilePath, stdout=tempFile, shell=True) 退出码是相同的,但在调试后我发现 dumpbin(或 cmd.exe)显示消息:“文件名、目录名或卷标语法不正确。” 并且调试显示当 shell=True 时,执行的命令是:C:\WINDOWS\system32\cmd.exe /c """C:\Program Files\Microsoft Visual Studio 8\VC\bin\dumpbin.exe" /EXPORTS C:\Window\system32\user32.dll"" - Hayri Uğur Koltuk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接