关于python:向cmd发送许多命令

sending many commands to cmd

我试图根据他发送给我的答案发送cmd许多命令。

我收到运行时错误消息:

1
ValueError: I/O operation on closed file

当我运行这样的东西时:

1
2
3
4
5
6
7
8
9
10
11
12
13
import subprocess
process = subprocess.Popen("cmd.exe", stdout=subprocess.PIPE,stdin=subprocess.PIPE)
answer = process.communicate(input="some command\
"
+ '\
'
)[0]

"""
choosing another command according to answer
"""


print process.communicate(input=another_command + '\
'
)[0]
process.kill()

关于如何解决问题有什么想法?

感谢您的帮助!


不要将命令发送到cmd.exe。 直接调用命令,例如:

1
subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE,stdin=subprocess.PIPE)

如果以这种方式使用它,则可能不需要stdin的管道。


错误是正常的。 communicate关闭子流程的标准输入,以指示没有其他输入待处理,以便子流程可以刷新其输出。 因此,您不能在一个子进程上链接多个communicate调用。

但是,如果您的命令足够简单(输入数据的字节数不多),并且在发送下一个命令之前不需要收集和处理一个命令的输出,则应该能够按顺序编写所有命令,并读取 他们两个之间尽可能多的输出。 在执行最后一条命令之后,您可以关闭子流程标准输入,并等待其终止,仍然对输出进行整理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
process = subprocess.Popen("cmd.exe", stdout=subprocess.PIPE, stdin=subprocess.PIPE)
process.stdin.write("some command\
\
"
)
partial_answer = process.stdout.read()  # all or part of the answer can still be buffered subprocess side
...
process.stdin.write("some other command\
\
"
)
...
# after last command, time to close subprocess
process.stdin.close()
retcode = None
while True:
    end_of_answer += process.stdout.read()
    if retcode is not None: break