0

假设我在当前位置有一个名为h33/的目录,我想删除它。在 shell 中我会输入rm -ri h33,它会消失。在python中我写道:

import subprocess
proc = subprocess.Popen(['rm','-ri','h33'],
    stdin=subprocess.PIPE, stdout=subprocess.PIPE)
proc.communicate('yes')

如果目录中没有任何文件,这很好用!因此,如果我运行相同的 linux 命令,我必须回答是进入文件夹,是删除我在那里的单个文件,然后是删除目录。所以我写道:

import subprocess
proc = subprocess.Popen(['rm','-ri','h33'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for i in range(3):
    proc.communicate('yes')

......它不起作用!不知道为什么。

rm: descend into directory ‘hr33’? rm: remove regular empty file ‘hr33/blank’? rm: remove directory ‘hr33’? Traceback (most recent call last):
  File "multiDel.py", line 6, in <module>
    proc.communicate("yes")
  File "/usr/lib/python2.7/subprocess.py", line 806, in communicate
    return self._communicate(input)
  File "/usr/lib/python2.7/subprocess.py", line 1377, in _communicate
    self.stdin.flush()
ValueError: I/O operation on closed file

我想做的主要事情是能够使用子流程来容纳多个输入(我希望这是有道理的)。请帮帮我

4

2 回答 2

0

Why not forcing the directory to be deleted without answering anything :

import subprocess
proc = subprocess.Popen(['rm','-rf','h33'],
    stdin=subprocess.PIPE, stdout=subprocess.PIPE)
于 2013-08-15T02:40:30.573 回答
0

.communicate()关闭管道并等待子进程退出,因此您最多可以调用它一次。假设rm只是一些接受输入的交互式程序的示例(否则,使用shutil.rmtree()rm -rf按照评论中的建议):

from subprocess import Popen, PIPE

proc = Popen(['rm','-ri','h33'], stdin=PIPE)
proc.communicate(b'yes\n' * 3)

或者你可以直接写信给proc.stdin

from subprocess import Popen, PIPE

proc = Popen(['rm','-ri','h33'], stdin=PIPE)
for i in range(3):
    proc.stdin.write(b'yes\n')
    proc.stdin.flush()
proc.communicate() # close pipes, wait for exit

pty通常,pexpect您可能需要模块来与子流程交互:

import pexpect # $ pip install pexpect

pexpect.run("rm -ri h33", events={r"'\?": "yes\n"}, timeout=30)

它假定需要yes回答的每个提示都以'?.

于 2013-08-16T09:37:40.207 回答