作为一个最小的例子,我想在远程和本地机器上运行“ping website.com”,并将两者的输出并行打印到本地stdout。
我使用多处理来调用两个函数并行运行。每个函数都使用subprocess.Popen(“ping ...”)。如果使用shell = True调用Popen,则仅打印一台机器的输出,最后打印另一台机器的输出。如果使用shell = False调用Popen,则输出将并行打印。为什么呢?
最小的例子(shell = True在第一个函数中):
#!/usr/bin/env python
import multiprocessing
import subprocess
import sys
import rpyc
def run_remote(ip, command, arg):
'''Connect to a pc using rpyc package, print remote stdout to local stdout.'''
remote_pc = rpyc.classic.connect(ip) # Connect
remote_pc.modules.sys.stdout = sys.stdout # Redirect remote stdout to local stdout
child = remote_pc.modules.subprocess.Popen([command, arg], shell=True, stdout=remote_pc.modules.subprocess.PIPE)
while True:
out = child.stdout.readline()
if out == '' and child.poll() != None:
break
if out != '':
print "%s" % out
remote_pc.modules.sys.stdout.flush()
def run_local(command, arg):
child = subprocess.Popen([command, arg], stdout=subprocess.PIPE)
while True:
out = child.stdout.readline()
if out == '' and child.poll() != None:
break
if out != '':
print "%s" % out
sys.stdout.flush()
if __name__ == '__main__':
print "Started."
remote_ip = "192.168.1.135" # must be running rpyc_classic.py
# CREATE PROCESSES
pc1 = multiprocessing.Process(target=run_remote, name="pc1", args=(remote_ip,"ping","yahoo.com"))
pc3 = multiprocessing.Process(target=run_local, name="pc3", args=("ping","google.com"))
# START PROCESSES
pc1.start()
pc3.start()
# WAIT FOR PROCESSES
pc1.join()
pc3.join()
print "Done."