"""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
您正在将
dstat
命令的CSV输出写入stats.csv
文件。在输出应该从
stats.csv
文件读取,而不是stdout,除非删除在命令中传递的output
选项。在在写下答案后,我想起有一种方法可以突破IPython,像个空壳一样奔跑。特别是,如果您的行以感叹号(
!
)开头,IPython将像在命令行上一样执行该命令。在例如,如果我运行
!dstat output stats.csv
,则得到以下结果:我仍然保留下面的基于自定义代码的方法,因为它的编写很有趣,但是显然,内置的解决方案(即,在命令前面加上
!
)可能更适合您的使用。在低于此点的自定义解决方案
这个怎么样?在
在Ubuntu上运行Python 3.7.3的IPython输出:
代码不是特别漂亮,但是可以很容易地将其放入自己的模块中,然后调用函数。我对IPython内部的结果相当满意。(输出感觉相当自然。)
相关问题 更多 >
编程相关推荐