Skip to main content
 首页 » 编程设计

python之从 Python 调用 Gnuplot

2025年05月04日15dyllove98

我正在尝试使用 python 脚本根据行号划分数据并调用 Gnuplot 绘制直方图。但是,出于某种原因,我在运行脚本后没有得到任何输出。 有人可以帮助我了解我做错了什么吗? 谢谢!

我的脚本:

#!/usr/bin/env python 
import os 
import subprocess 
with open("gpu Latency sample 1.txt", "r") as f: 
        for lineno, line in enumerate(f, start=1): 
                if ( lineno % 2 == 0) : 
                        #odd_file = open("odd_file.txt", 'a') 
                        with open("even.txt", "a") as even_file: 
                            even_file.write(line) 
                else : 
                        with open("odd.txt", "a") as odd_file: 
                            odd_file.write(line) 
p = subprocess.Popen(['gnuplot'], shell = True,stdin=subprocess.PIPE ) 
filename1= open("even.txt","r") 
filename2= open("odd.txt","r") 
p.stdin.write("set xtics nomirror rotate by -45") 
p.stdin.write("set key noenhanced") 
p.stdin.write("set style data linespoints") 
p.stdin.write("binwidth=1000") 
p.stdin.write("bin(x, width)=width*floor(x/width) + binwidth/2.0") 
p.stdin.write("plot \"%s\" using (bin((\$1+\$2),binwidth)): (1.0) smooth freq with lines, \"%s\" using (bin((\$1+\$2),binwidth)): (1.0) smooth freq with lines" %(filename1, filename2)) 
p.stdin.write("pause -1") 

请您参考如下方法:

您正在写入 gnuplot 的标准输入,但您没有向它发送任何换行符 (\n):您所有的 gnuplot 命令都在一行中被取消,它们之间甚至没有空格。

只需在上面的每个 write 调用的末尾添加一个 "\n" 字符即可。