Python子进程:如何管道到gnuplot命令来绘制变量?

Æle*_*lex 1 python subprocess escaping gnuplot string-formatting

我不想在这里做任何想象.我试图在以下脚本中自动绘制一些实验数据:

print "processing: ", filename

gnuplot = Popen(gnuplot_bin,stdin = PIPE).stdin

if state_plot:

        gnuplot.write( "set term x11\n".encode())
        gnuplot.write( "set term png size 1920,1010 \n".encode() )
        gnuplot.write( "set output \"acceleration.png\" \n".encode() )
        gnuplot.write( "set xlabel \"timesteps\" \n".encode() )
        gnuplot.write( "set ylabel \"acceleration\" \n".encode() )
        gnuplot.write( "plot " %filename " using 1 with lines lt -1 lw 0.5 title 'X axis' \n " .encode() )
        gnuplot.write( " " %filename " using 2 with lines lt 1 lw 0.5 title 'Y axis'  \n " .encode() )
        gnuplot.write( " " %filename " using 3 with lines lt 2 lw 0.5 title 'Z axis' \n " .encode() )
Run Code Online (Sandbox Code Playgroud)

但是文件名是字面意思.我从gnuplot收到以下错误:

第0行:警告:跳过不可读的文件""%filename""第0行:图中没有数据

我已经从sys.argv解析了文件名,并确保它是正确和安全的,现在我需要告诉gnuplot绘制文件名设置的名称.我已经尝试使用转义字符,删除了ambersand,但我显然使用了错误的语法.

有人可以帮忙吗?

编辑:

感谢agf我已经解决了python格式问题:

gnuplot.write( "plot \"%s\" using 1 with lines lt -1 lw 0.5 title 'X axis' ,\ \n " %filename )
        gnuplot.write( "\"%s\" using 2 with lines lt 1 lw 0.5 title 'Y axis' ,\ \n " %filename )
        gnuplot.write( "\"%s\" using 3 with lines lt 2 lw 0.5 title 'Z axis' \n " %filename )
Run Code Online (Sandbox Code Playgroud)

但是现在我遇到了gnuplot的问题.通常在直接使用gnuplot时,我会输入:

gnuplot> plot "state_log_6548032.data" using 4 with lines lt -1 lw 0.5 title "X axis" ,\
>"state_log_6548032.data" using 5 with lines lt 1 lw 0.5 title "Y axis" ,\
>"state_log_6548032.data" using 6 with lines lt 2 lw 0.5 title "Z axis"
Run Code Online (Sandbox Code Playgroud)

但是,通过python将这些命令发送到gnuplot似乎会导致错误:

gnuplot> plot "state_log_6548032.data" using 1 with lines lt -1 lw 0.5 title 'X axis' ,\ 
                                                                                       ^
         line 0: invalid character \

gnuplot> "state_log_6548032.data" using 2 with lines lt 1 lw 0.5 title 'Y axis' ,\ 
                                                                                 ^
         line 0: invalid character \

gnuplot> "state_log_6548032.data" using 3 with lines lt 2 lw 0.5 title 'Z axis' 
         ^
         line 0: invalid command
Run Code Online (Sandbox Code Playgroud)

我打赌它与\,换行符有什么关系?

agf*_*agf 5

你要

    gnuplot.write("plot %s using 1 with lines lt -1 lw 0.5 title 'X axis' \n " % filename1)
Run Code Online (Sandbox Code Playgroud)

http://docs.python.org/library/string.html#formatstrings新样式格式和http://docs.python.org/library/stdtypes.html#string-formatting旧样式格式,它看起来像你想做什么.

编辑2:我也喜欢维索的一部分建议.将gnuplot命令保存在一个文件中(使用您需要输入的变量的格式代码),然后用Python读取该文件并对其进行格式化.这分隔了gnuplot的东西,你不必担心引用或行结尾.

如果你想发送很多命令,我会尝试将所有字符串写入列表(最好是从文件中读取file.readlines())然后:

for line in lines:
    gnuplot.write(lines)
    gnuplot.flush()
Run Code Online (Sandbox Code Playgroud)

因此,它一次只发送一行,但您不必硬编码某个数字.