python 关于subprocess.Popen循环进行子进程

柴星星 2019-01-29 09:19:21
import subprocess
def run():
files = ['1.txt', '2.txt', '3.txt']
for file in files:
p = subprocess.Popen('cmd命令'+file, stdout=subprocess.PIPE, shell=False, universal_newlines=True)

问题是:我想第一个命令执行完毕后再执行第二个然后再第三个,实际上这三个会同时处于运行状态。
求助:我该怎么做才能让这三个命令按顺序执行?并且同时主进程不要阻塞,主进程还在通过管道读取输出,并反馈给图形界面的进度条。
...全文
684 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
好想长大 2019-03-05
  • 打赏
  • 举报
回复
self.p.wait()
ruancan 2019-01-31
  • 打赏
  • 举报
回复
引用 4 楼 木九 的回复:
[quote=引用 3 楼 ruancan 的回复:]
你到底是要顺序执行还是并行执行?

顺序执行,在上一个执行完毕后,再执行下一个。这个命令会对磁盘进行读写,多个并行怕磁盘IO变得太慢了[/quote]
那我上边的代码不是正好满足你的要求吗?
柴星星 2019-01-31
  • 打赏
  • 举报
回复
引用 3 楼 ruancan 的回复:
你到底是要顺序执行还是并行执行?

顺序执行,在上一个执行完毕后,再执行下一个。这个命令会对磁盘进行读写,多个并行怕磁盘IO变得太慢了
ruancan 2019-01-31
  • 打赏
  • 举报
回复
你到底是要顺序执行还是并行执行?
柴星星 2019-01-31
  • 打赏
  • 举报
回复
大佬们,求救。我又尝试了把每个popen休眠起来,然后在一次唤醒,但是还是会挨个运行,怎么让循环那等等,或者怎么执行CMD没有子进程呢
ruancan 2019-01-30
  • 打赏
  • 举报
回复
代码如下: Windows下边亲测可行,linux需要把encoding='gbk'改为utf-8

import subprocess


class RunCMD:
    def __init__(self):
        self.p = None
        self.cmd = None

    def run_cmd(self):
        self.p = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

    @property
    def is_running(self):
        if self.p.poll() is None:
            return True
        else:
            return False

    def stop(self):
        self.p.kill()

    def log(self):
        return ''.join([str(item, encoding='gbk') for item in self.p.communicate()])


if __name__ == "__main__":
    files = ['ping 127.0.0.1', 'ping www.baidu.com', 'ping ping www.163.com']
    for file in files:
        runner = RunCMD()
        runner.cmd = file
        runner.run_cmd()
        print(runner.log())

37,741

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧