我如何在python中使用子进程模块(在外部程序保持运行的同时)动态地实现输出。我要从中动态获取输出的外部程序是ngrok,
只要我的程序正在运行,ngrok就会一直运行,但是在进程运行时我需要输出,以便可以提取新生成的“转发url”
当我尝试做时:
cmd = ['ngrok', 'http', '5000']
output = subprocess.Popen(cmd, stdout=subprocess.PIPE, buffersize=1)
它一直将输出存储在缓冲区中
参考方案
我知道这是重复的,但现在找不到与此相关的任何线程。我得到的只是output.communicate()
。
因此,以下片段可能会有用:
import subprocess
cmd = ['ngrok', 'http', '5000']
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while process.poll() is None:
print(process.stdout.readline())
print(process.stdout.read())
process.stdout.close()
这将通过脚本将过程输出的任何内容输出到输出中。它是通过在输出之前寻找换行符来实现的。
如果不是因为ngrok
使用ncurses和/或将输出输出到其自己的用户/线程中,这部分代码就可以工作,就像在执行ssh user@host
时SSH要求输入密码时一样。
process.poll()
检查进程是否具有退出代码(如果已死),否则,它将继续循环并打印来自进程stdout
的任何内容。
还有其他(更好的)解决方法,但这是我可以给您的最低要求,而不必太复杂。
例如,process.stdout.read()
可以与select.select()
结合使用,以在出现换行符的地方获得更好的缓冲输出。因为如果\n
永远不会出现,则上面的示例可能会挂起整个应用程序。
在执行此类手动操作之前,您需要了解很多缓冲区陷阱。否则,请改用process.communicate()
。
编辑:要解决ngrok使用的I / O的限制/限制,可以使用pty.fork()
并通过os.read
模块读取childsstdout:
#!/usr/bin/python
## Requires: Linux
## Does not require: Pexpect
import pty, os
from os import fork, waitpid, execv, read, write, kill
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid < 0:
return False
try:
kill(pid, 0)
except (OSError, e):
return e.errno == errno.EPERMRM
else:
return True
class exec():
def __init__(self):
self.run()
def run(self):
command = [
'/usr/bin/ngrok',
'http',
'5000'
]
# PID = 0 for child, and the PID of the child for the parent
pid, child_fd = pty.fork()
if not pid: # Child process
# Replace child process with our SSH process
execv(command[0], command)
while True:
output = read(child_fd, 1024)
print(output.decode('UTF-8'))
lower = output.lower()
# example input (if needed)
if b'password:' in lower:
write(child_fd, b'some response\n')
waitpid(pid, 0)
exec()
这里仍然存在问题,我不确定是什么原因或原因。
我猜该进程正在等待信号/如何刷新。
问题在于,它仅打印ncurses的第一个“设置数据”,这意味着它会擦拭屏幕并设置背景色。
但这至少会给您过程的输出。替换print(output.decode('UTF-8'))
将显示输出内容。
我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
如何用'-'解析字符串到节点js本地脚本? - python我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…
Python:传递记录器是个好主意吗? - python我的Web服务器的API日志如下:started started succeeded failed 那是同时收到的两个请求。很难说哪一个成功或失败。为了彼此分离请求,我为每个请求创建了一个随机数,并将其用作记录器的名称logger = logging.getLogger(random_number) 日志变成[111] started [222] start…
Python-Excel导出 - python我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…
Matplotlib'粗体'字体 - python跟随this example:import numpy as np import matplotlib.pyplot as plt fig = plt.figure() for i, label in enumerate(('A', 'B', 'C', 'D')): ax = f…