让 Python 打印到命令行(图形可视化命令 gvpr 的输出)



我正在尝试让 Python 运行此命令,该命令在我的命令提示符下运行良好:

ccomps -x rel_graph.dot | gvpr -c "N[nNodes($G)<5]{delete(0,$)}" | dot | gvpack | sfdp -Goverlap=prism | gvmap -e | gvpr "BEGIN{int m,w,e = 0} N[fontcolor=='blue']{m += 1} N[fontcolor=='green']{e += 1} N[fontcolor=='red']{w += 1} END{print(m); print(w); print(e);}"

在Python中,我正在使用:

temp = subprocess.Popen("""ccomps -x rel_graph.dot | gvpr -c 
    "N[nNodes($G)<5]{delete(0,$)}" | dot | gvpack | sfdp -Goverlap=prism 
    | gvmap -e | gvpr 'BEGIN{int m,w,e = 0} 
    N[fontcolor=="blue"]{m += 1} 
    N[fontcolor=="green"]{e += 1} 
    N[fontcolor=="red"]{w += 1} 
    END{print(m); print(w); print(e);}'
    """, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

。然后从临时读取/打印行。问题是 Python 没有将最后三个打印语句(都是整数)打印到标准输出,或者至少我找不到它。gvpr程序的其余部分在Python上运行良好。

谢谢!

经过更多的工作,我将 BEGIN 引号更改为双引号,将所有内部参数更改为单引号,这似乎已经解决了这个问题。

你可以将 stdout \ stderr 发送到像这样的文件 -

from subprocess import Popen
std_out_file = "/tmp/stdout.log"
std_err_file = "/tmp/stderr.log"
command_to_execute = "<your-command>"
with open(std_out_file, "wb") as out, open(std_err_file, "wb") as err:
        p = Popen(command_to_execute, shell=True, cwd=<folder>, stdout=out, stderr=err)
p.communicate()

然后你从文件中读取 stdout \ stderr,例如:

f = open(std_out_file, "r")
stdout = f.readlines()
f.close()   

你可以检查命令的返回码,检查你是否还需要像这样打印 stdrr——

if p.returncode == 0:

最新更新