显示来自的输出子流程.Popen仿佛在终点站奔跑

2024-04-24 02:41:40 发布

您现在位置:Python中文网/ 问答频道 /正文

  subprocess.Popen('dstat --output stats.csv', shell=True, stdout=subprocess.PIPE).stdout.read()

我正在使用ipython,当我运行上面的命令时,控制台上不会打印任何内容。有没有一种方法可以在控制台窗口中看到与直接在linux终端上运行命令时相同的输出?在


Tags: csv方法命令true内容readoutputstats
2条回答

您正在将dstat命令的CSV输出写入stats.csv文件。在

输出应该从stats.csv文件读取,而不是stdout,除非删除在命令中传递的 output选项。在

在写下答案后,我想起有一种方法可以突破IPython,像个空壳一样奔跑。特别是,如果您的行以感叹号(!)开头,IPython将像在命令行上一样执行该命令。在

例如,如果我运行!dstat output stats.csv,则得到以下结果:

Using Exclamation Mark to Break Out of IPython

我仍然保留下面的基于自定义代码的方法,因为它的编写很有趣,但是显然,内置的解决方案(即,在命令前面加上!)可能更适合您的使用。在


低于此点的自定义解决方案

这个怎么样?在

"""Simulate command-line execution."""
import os
import sys
import subprocess
import signal
from time import sleep


def local_command(command):
    """Simulate command execution as if on command-line."""
    env_to_pass = dict(os.environ)
    kwargs_for_popen = {
        'shell': True,
        'bufsize': 1,
        'stdin': sys.stdin.fileno(),
        'stdout': sys.stdout.fileno(),
        'stderr': sys.stderr.fileno(),
        'env': env_to_pass
    }
    # Determine which keyword we should use for putting the process I/O into
    # text-only mode.
    if sys.hexversion >= 0x3070000:
        # "text" was added as a keyword argument alias for "universal_newlines"
        # in Python 3.7, and "universal_newlines" is provided still only for
        # backwards compatibility. Let's do this right if we're going to do it.
        kwargs_for_popen['text'] = True
    else:
        # For systems with python before 3.7, use "universal_newlines"
        kwargs_for_popen['universal_newlines'] = True

    sp = subprocess.Popen(command, **kwargs_for_popen)
    while True:
        try:
            while sp.poll() is None:
                sleep(0.02)
        except KeyboardInterrupt:
            sp.send_signal(signal.SIGINT)
            sleep(0.02)
        if sp.poll() is not None:
            # Process has terminated.
            # Exit event loop.
            break
    # end while

    sp_stdout_data, sp_stderr_data = sp.communicate()
    print(sp_stdout_data)
    return sp.returncode

在Ubuntu上运行Python 3.7.3的IPython输出:

Output of Running Local Command Using Code in Answer in IPython

代码不是特别漂亮,但是可以很容易地将其放入自己的模块中,然后调用函数。我对IPython内部的结果相当满意。(输出感觉相当自然。)

相关问题 更多 >