noa*_*ahd 27 python rsync multithreading subprocess
我正在尝试使用子进程模块和线程内的Popen启动'rsync'.在我调用rsync之后,我还需要读取输出.我正在使用通信方法来读取输出.我不使用线程时代码运行正常.看来,当我使用一个线程时,它会挂在通信呼叫上.我注意到的另一件事是,当我设置shell = False时,在线程中运行时,我从通信中得不到任何回报.
Rya*_*ght 39
您没有提供任何代码供我们查看,但这里的示例与您描述的内容类似:
import threading
import subprocess
class MyClass(threading.Thread):
def __init__(self):
self.stdout = None
self.stderr = None
threading.Thread.__init__(self)
def run(self):
p = subprocess.Popen('rsync -av /etc/passwd /tmp'.split(),
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.stdout, self.stderr = p.communicate()
myclass = MyClass()
myclass.start()
myclass.join()
print myclass.stdout
Run Code Online (Sandbox Code Playgroud)
小智 13
这是一个不使用线程的优秀实现: 不断打印 - 子进程 - 输出 - 进程正在运行
import subprocess
def execute(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ''
# Poll process for new output until finished
for line in iter(process.stdout.readline, ""):
print line,
output += line
process.wait()
exitCode = process.returncode
if (exitCode == 0):
return output
else:
raise Exception(command, exitCode, output)
execute(['ping', 'localhost'])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53788 次 |
| 最近记录: |