【问题标题】:Getting pv output with subprocess使用子进程获取 pv 输出
【发布时间】:2018-12-30 22:21:27
【问题描述】:

我正在编写一个脚本来自动化 MySQL 中的数据库导入。我正在尝试编写在导入数据库时​​显示pv 输出的代码:

    pv = subprocess.Popen(
        ["pv", "-f", restore_filepath],
        bufsize=1,
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE,
        universal_newlines=True,
        shell=True,
    )
    subprocess.Popen(
        [
            "mysql",
            "-u{}".format(db_user),
            "-p{}".format(db_pass),
            db_name,
        ],
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.DEVNULL,
        stdin=pv.stdout,
    )
    for line in pv.stderr:
        print("hello")
        sys.stdout.write("\r" + line.rstrip("\n"))
        sys.stdout.flush()

这是基于this question 中的代码,但它不适用于我。 hello 甚至不会被打印出来,即使我注释掉 for 循环中的其他行 - for line in pv.stderr 是阻塞的,我不知道为什么。它永远不会解除阻塞,所以即使进程完成,程序仍然卡住 - 我必须杀死它。

我做错了什么导致for line in pv.stderr 被阻止?

【问题讨论】:

  • 第二个被丢弃的Popen 是怎么回事?

标签: python subprocess pv


【解决方案1】:

When shell=Trueargs[0] 是要执行的命令,args[1:] 是传递给sh 的参数。您希望将 -prestore_filepath 传递给 pv 而不是 sh。所以使用shell=False。您的另一个 subprocess.Popen 电话也是如此。

由于shell=True,pv 没有收到任何参数,所以它挂起,因为它仍在等待文件名。再说一遍,解决方案是使用shell=False

还要注意replacing a shell pipeline,如果存在第二个进程,你应该关闭第一个进程上的stdout,以允许它接收 SIGPIPE。这允许一些程序(那些处理 SIGPIPE 的程序)在管道中断时更优雅地退出。

pv = subprocess.Popen(
    ["pv", "-f", restore_filepath],
    shell=False,  # optional, since this is the default
    bufsize=1,
    stderr=subprocess.PIPE,
    stdout=subprocess.PIPE,
    universal_newlines=True,
)
mysql = subprocess.Popen(
    ["mysql",
     "-u{}".format(db_user),
     "-p{}".format(db_pass),
     db_name],
    shell=False,
    stdout=subprocess.PIPE,
    stderr=subprocess.DEVNULL,
    stdin=pv.stdout,
)
pv.stdout.close() # Allow pv to receive a SIGPIPE if mysql exits. 
for line in pv.stderr:
    print("hello")
    sys.stdout.write("\r" + line.rstrip("\n"))
    sys.stdout.flush()

【讨论】:

    猜你喜欢
    • 2015-12-07
    • 1970-01-01
    • 2010-10-22
    • 2019-01-25
    • 2011-09-08
    • 2020-03-03
    相关资源
    最近更新 更多