我正在使用子进程模块启动子进程并连接到它的输出流(stdout).我希望能够在其标准输出上执行非阻塞读取.有没有办法让.readline非阻塞或在我调用之前检查流上是否有数据.readline?我希望这是可移植的,或至少在Windows和Linux下工作.
这是我现在如何做到的(.readline如果没有数据可用,则阻止它):
p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE)
output_str = p.stdout.readline()
Run Code Online (Sandbox Code Playgroud) 我有以下代码将md5sums写入日志文件
for file in files_output:
p=subprocess.Popen(['md5sum',file],stdout=logfile)
p.wait()
Run Code Online (Sandbox Code Playgroud)
这些是并行写的吗?即如果md5sum对其中一个文件花费很长时间,那么在等待前一个文件完成之前是否会启动另一个文件?
如果上面的答案是肯定的,我可以假设写入日志文件的md5sums的顺序可能因md5sum对每个文件的使用时间而有所不同吗?(有些文件可能很大,有些文件很小)
好的,我试图从python脚本运行一个C程序.目前我正在使用测试C程序:
#include <stdio.h>
int main() {
while (1) {
printf("2000\n");
sleep(1);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
模拟我将要使用的程序,它不断地从传感器获取读数.然后我试图"2000"从C程序读取输出(在这种情况下)与python中的子进程:
#!usr/bin/python
import subprocess
process = subprocess.Popen("./main", stdout=subprocess.PIPE)
while True:
for line in iter(process.stdout.readline, ''):
print line,
Run Code Online (Sandbox Code Playgroud)
但这不起作用.从使用print语句开始运行该.Popen行然后等待for line in iter(process.stdout.readline, ''):,直到我按下Ctrl-C.
为什么是这样?这正是我见过的大多数示例都是他们的代码,但它没有读取文件.
编辑:
有没有办法让它只在有东西被阅读时才能运行?
我cat | zgrep在远程服务器上运行几个命令并单独收集它们的输出以进行进一步处理:
class MainProcessor(mp.Process):
def __init__(self, peaks_array):
super(MainProcessor, self).__init__()
self.peaks_array = peaks_array
def run(self):
for peak_arr in self.peaks_array:
peak_processor = PeakProcessor(peak_arr)
peak_processor.start()
class PeakProcessor(mp.Process):
def __init__(self, peak_arr):
super(PeakProcessor, self).__init__()
self.peak_arr = peak_arr
def run(self):
command = 'ssh remote_host cat files_to_process | zgrep --mmap "regex" '
log_lines = (subprocess.check_output(command, shell=True)).split('\n')
process_data(log_lines)
Run Code Online (Sandbox Code Playgroud)
但是,这会导致子进程('ssh ... cat ...')命令的顺序执行.第二个峰值等待第一个完成,依此类推.
如何修改此代码以便子进程调用并行运行,同时仍能够单独收集每个的输出?
我在linux下有一个可执行文件.我有一个8核处理器.我想用不同的参数运行相同可执行文件的8个不同实例.
我试过了
os.system("process_name args")
Run Code Online (Sandbox Code Playgroud)
在该过程完成之前它不会返回.
我想从python开始8个不同的进程
如果有人可以帮助我.
非常感谢
我有一个Python脚本,必须调用某个应用3次。这些调用应该是并行的,因为它们需要几个小时才能完成,并且彼此之间不相干。但是它们的脚本应该停止运行,直到它们全部完成,然后再进行一些清理工作。
这是一些代码:
#do some stuff
for work in worklist: # these should run in parralel
output=open('test.txt','w')
subprocess.call(work,stdout=output,stderr=output)
output.close()
# wait for subprocesses to finish
# cleanup
Run Code Online (Sandbox Code Playgroud)
所以我基本上想在捕获其输出到文件中的同时运行此命令。完成所有实例后,我要继续执行脚本