为什么subprocess.Popen不起作用

7 投票
2 回答
18040 浏览
提问于 2025-04-17 04:37

我尝试了很多方法,但不知道为什么就是无法让它们正常工作。我想用一个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()

有没有人知道我想做的事情(dumpbin /EXPORTS C:\Windows\system32\kernel32.dll > tempfile.txt)在Python中该怎么正确实现?

2 个回答

2

在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后把它放到另一个地方。这就像把水从一个杯子倒到另一个杯子一样。

有些时候,我们会遇到一些问题,比如数据格式不对,或者数据不完整。这就像你想把果汁倒进一个小杯子,但果汁太多了,杯子装不下。

为了避免这些问题,我们可以使用一些工具或者方法来检查数据,确保它们是正确的。这样就能顺利地把数据从一个地方转移到另一个地方,而不会出错。

总之,处理数据就像做一个小实验,我们需要仔细观察,确保每一步都做对,这样才能得到想要的结果。

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

Popen的参数格式对于非shell调用来说需要一个字符串列表,而对于shell调用则需要一个字符串。这一点很简单可以解决。假设有:

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

你可以通过在调用subprocess.Popen时设置shell=True来解决这个问题:

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

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

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

撰写回答