从命令行调用程序时,我可以管道输出grep以选择我想要查看的行,例如
printf "hello\ngood day\nfarewell\n" | grep day
Run Code Online (Sandbox Code Playgroud)
我正在寻找相同类型的行选择,但是对于从Python调用的C库.请考虑以下示例:
import os
# Function which emulate a C library call
def call_library():
os.system('printf "hello\ngood day\nfarewell\n"')
# Pure Python stuff
print('hello from Python')
# C library stuff
call_library()
Run Code Online (Sandbox Code Playgroud)
运行这个Python代码时,我希望C部分的输出grep为字符串的ed 'day',从而产生代码的输出
你好,从Python
好日子
到目前为止,我已经stdout使用此处和此处描述的方法摆弄了重定向.我能够使C输出完全消失,或将其保存到a str并稍后打印出来(这是两个链接主要关注的内容).然而,我无法根据其内容选择打印哪些行.重要的是,我希望在调用C库时实时输出,所以我不能只是重定向stdout到某个缓冲区并在事后对此缓冲区进行一些处理.
该解决方案只需要在Linux上使用Python 3.x. 如果除了行选择之外,该解决方案还可以进行行编辑,甚至可以更大.
重定向stdout到内存中的"文件".
生成一个不断从该文件读取的新线程,根据行内容进行选择,并将所需行写入屏幕,即原始目标stdout.
调用C库
将两个线程重新连接在一起并重定向stdout回其原始目标(屏幕).
我对文件描述符等没有足够的把握能够做到这一点,甚至不知道这是否是最好的方法.
请注意,解决方案不能简单地重新实现代码call_library.代码必须调用 …
我必须打开一个系统文件并从中读取。这个文件通常只能被 root(超级用户)读取。我有办法向用户询问超级用户密码。我想使用此凭据打开文件并从中读取,而无需将整个程序作为超级用户进程运行。有没有办法以多平台的方式实现这一目标?
我有一个 Apache Web 服务器,我制作了一个 python 脚本来运行命令。我正在运行的命令正在启动一个 ROS 启动文件,该文件无限期地工作。我想实时读取子流程的输出并将其显示在页面中。到目前为止,我的代码只能在终止进程后才能打印输出。我已经尝试了网络上的各种解决方案,但似乎都不起作用
command = "roslaunch package test.launch"
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env,
shell=True,
bufsize=1,
)
print "Content-type:text/html\r\n\r\n"
for line in iter(proc.stdout.readline, ''):
strLine = str(line).rstrip()
print(">>> " + strLine)
print("<br/>")
Run Code Online (Sandbox Code Playgroud) 我正在尝试从python Windows应用程序运行一个python文件。为此,我使用了subprocess。为了在应用程序控制台上获得实时流输出,我尝试了以下语句。
带PIPE
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, shell=True)
for line in iter(p.stdout.readline, ''):
print line
Run Code Online (Sandbox Code Playgroud)
(要么)
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
out = process.stdout.read(1)
if out == '' and process.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
不仅上面的代码尝试了很多方法。获得如下相同的结果:
1.Python Windows应用程序花费大量时间运行
2.然后,应用程序窗口长时间处于“无响应”状态
3.然后将整个输出打印在控制台上
我知道python应用程序中正在发生缓冲区溢出,这就是为什么我没有实时输出的原因。
我为此发布了很多查询,但仍然没有解决方案。
刚刚找到并尝试了这个的tempfile。但是我不确定这将提供实时流输出。
我可以这样尝试吗?
import tempfile
import subprocess
w = tempfile.NamedTemporaryFile()
p = subprocess.Popen(cmd, shell=True, stdout=w,
stderr=subprocess.STDOUT, bufsize=0)
with open(w.name, 'r') as r:
for line in r:
print line
w.close() …Run Code Online (Sandbox Code Playgroud) python ×3
python-2.7 ×2
apache ×1
c ×1
file-io ×1
grep ×1
linux ×1
pipe ×1
python-3.x ×1
ros ×1
subprocess ×1