使用Python从应用程序读取初始屏幕

问题描述 投票:0回答:1

我正在尝试通过子进程模块读取和打印 gnuplot 的初始屏幕:

G N U P L O T
Version 4.6 patchlevel 4    last modified 2013-10-02 
Build System: Linux x86_64
Copyright (C) 1986-1993, 1998, 2004, 2007-2013
Thomas Williams, Colin Kelley and many others
gnuplot home:     http://www.gnuplot.info
faq, bugs, etc:   type "help FAQ"
immediate help:   type "help"  (plot window: hit 'h')
Terminal type set to 'wxt'

这是我的代码:

from subprocess 
import PIPE, Popen
import fcntl, os
class Gnuplot:
def __init__(self, debug=True):
    self.debug = debug
    if self.debug:
        print 'Initializing ...\n' 
    # start process    
    self.proc = subprocess.Popen(['gnuplot'],stdin=PIPE,stdout=PIPE,stderr=PIPE)  
    # set stderr as nonblocking so that we can skip when there is nothing
    fcntl.fcntl(self.proc.stderr.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
#a = self.proc.communicate()
    fcntl.fcntl(self.proc.stderr.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
    cout = self.proc.communicate()
    if self.debug:
        print 'Done!\n'
    print cout
g= Gnuplot()

我不知道我的错在哪里。我该如何解决这个问题?

python subprocess pipe gnuplot
1个回答
0
投票

这对我来说适用于 python 2 和 3、linux 和 windows(除了 gnuplot 之外):

import subprocess
import fcntl
import os
import select


proc = subprocess.Popen(['gnuplot'],
                    stderr=subprocess.PIPE,
                    close_fds=True,
                    universal_newlines=True)
fcntl.fcntl(
    proc.stderr.fileno(),
    fcntl.F_SETFL,
    fcntl.fcntl(proc.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK)

status = select.select([proc.stderr.fileno()], [], [])[0]
if status:
    out = proc.stderr.read()
print(out)
proc.kill()
© www.soinside.com 2019 - 2024. All rights reserved.