Programing

gnuplot에 명령 줄 인수를 전달하는 방법은 무엇입니까?

lottogame 2020. 6. 23. 07:39
반응형

gnuplot에 명령 줄 인수를 전달하는 방법은 무엇입니까?


gnuplot을 사용하여 foo.data 와 같은 데이터 파일에서 그림을 그립니다 . 현재 명령 파일에 foo.plt같은 데이터 파일 이름을 하드 코딩하고 명령 gnuplot foo.plg실행 하여 데이터를 플로팅했습니다. 그러나 데이터 파일 이름을 명령 인수로 전달하고 싶습니다 (예 : running command) gnuplot foo.plg foo.data. gnuplot 스크립트 파일에서 명령 줄 인수를 구문 분석하는 방법은 무엇입니까? 감사.


스위치를 통해 변수를 입력 할 수 있습니다 -e

$ gnuplot -e "filename='foo.data'" foo.plg

foo.plg에서 그 변수를 사용할 수 있습니다

$ cat foo.plg 
plot filename
pause -1

"foo.plg"를 좀 더 일반적으로 만들려면 조건부를 사용하십시오.

if (!exists("filename")) filename='default.dat'
plot filename
pause -1

참고 -e파일 이름을 선행해야한다, 그렇지 않으면 파일이 실행되기 전에 -e문. 특히 CLI 인수 #!/usr/bin/env gnuplot와 함께 shebang gnuplot 실행하면 ./foo.plg -e ...제공된 인수 사용이 무시됩니다.


버전 5.0부터 gnuplot 스크립트에 플래그를 사용하여 인수를 전달할 수 있습니다 -c. 이 인수는 변수를 통해 액세스 ARG0ARG9, ARG0스크립트 및 인 ARG1ARG9문자열 변수. 인수 수는로 제공됩니다 ARGC.

예를 들어 다음 스크립트 ( "script.gp")

#!/usr/local/bin/gnuplot --persist

THIRD=ARG3
print "script name        : ", ARG0
print "first argument     : ", ARG1
print "third argument     : ", THIRD 
print "number of arguments: ", ARGC 

다음과 같이 호출 할 수 있습니다.

$ gnuplot -c script.gp one two three four five
script name        : script.gp
first argument     : one
third argument     : three
number of arguments: 5

또는 gnuplot 내에서

gnuplot> call 'script.gp' one two three four five
script name        : script.gp
first argument     : one
third argument     : three
number of arguments: 5

gnuplot 4.6.6 및 이전 버전 call에는 다른 (더 이상 사용되지 않는) 구문 메커니즘 이 있습니다 . 인수를 통해 액세스 할 수 있습니다 $#, $0, ..., $9. 예를 들어 위의 동일한 스크립트는 다음과 같습니다.

#!/usr/bin/gnuplot --persist

THIRD="$2"
print "first argument     : ", "$0"
print "second argument    : ", "$1"
print "third argument     : ", THIRD
print "number of arguments: ", "$#"

gnuplot 내에서 다음과 같이 호출됩니다 (버전 <4.6.6 기억)

gnuplot> call 'script4.gp' one two three four five
first argument     : one
second argument    : two
third argument     : three
number of arguments: 5

스크립트 이름에 대한 변수가 없으므로 $0첫 번째 인수도 있으며 따옴표 안에 변수가 호출됩니다. @ con-fu-se가 제안한 트릭을 통해서만 명령 줄에서 직접 사용할 수는 없습니다.


여기 에 제안 된대로 환경을 통해 정보를 전달할 수도 있습니다 . Ismail Amin 의 예제 는 여기에서 반복됩니다.

쉘에서 :

export name=plot_data_file

Gnuplot 스크립트에서 :

#! /usr/bin/gnuplot

name=system("echo $name")
set title name
plot name using ($16 * 8):20 with linespoints notitle
pause -1

Jari Laamanen의 답변이 최고의 솔루션입니다. 쉘 변수와 함께 둘 이상의 입력 매개 변수를 사용하는 방법을 설명하고 싶습니다.

output=test1.png
data=foo.data
gnuplot -e "datafile='${data}'; outputname='${output}'" foo.plg

그리고 foo.plg :

set terminal png
set outputname 
f(x) = sin(x)
plot datafile

보다시피, bash 스크립트와 같이 세미콜론으로 더 많은 매개 변수가 전달되지만 문자열 변수 NEED는 ''(gnuplot 구문, NOT Bash 구문)으로 캡슐화되어야합니다.


유닉스 / 리눅스 환경에서 트릭을 사용할 수 있습니다 :

  1. in gnuplot program: plot "/dev/stdin" ...

  2. In command line: gnuplot program.plot < data.dat


This question is well answered but I think I can find a niche to fill here regardless, if only to reduce the workload on somebody googling this like I did. The answer from vagoberto gave me what I needed to solve my version of this problem and so I'll share my solution here.

I developed a plot script in an up-to-date environment which allowed me to do:

#!/usr/bin/gnuplot -c 
set terminal png truecolor transparent crop
set output ARG1
set size 1, 0.2
rrLower = ARG2
rrUpper = ARG3
rrSD = ARG4
resultx = ARG5+0 # Type coercion required for data series
resulty = 0.02 # fixed
# etc.

This executes perfectly well from command-line in an environment with a recent gnuplot (5.0.3 in my case).

$ ./plotStuff.gp 'output.png' 2.3 6.7 4.3 7

When uploaded to my server and executed, it failed because the server version was 4.6.4 (current on Ubuntu 14.04 LTS). The below shim solved this problem without requiring any change to the original script.

#!/bin/bash
# GPlot v<4.6.6 doesn't support direct command line arguments.
#This script backfills the functionality transparently.
SCRIPT="plotStuff.gp"
ARG1=$1
ARG2=$2
ARG3=$3
ARG4=$4
ARG5=$5
ARG6=$6

gnuplot -e "ARG1='${ARG1}'; ARG2='${ARG2}'; ARG3='${ARG3}'; ARG4='${ARG4}'; ARG5='${ARG5}'; ARG6='${ARG6}'" $SCRIPT

The combination of these two scripts allows parameters to be passed from bash to gnuplot scripts without regard to the gnuplot version and in basically any *nix.


You could even do some shell magic, e.g. like this:

#!/bin/bash
inputfile="${1}" #you could even do some getopt magic here...

################################################################################
## generate a gnuplotscript, strip off bash header
gnuplotscript=$(mktemp /tmp/gnuplot_cmd_$(basename "${0}").XXXXXX.gnuplot)

firstline=$(grep -m 1 -n "^#!/usr/bin/gnuplot" "${0}")
firstline=${firstline%%:*} #remove everything after the colon
sed -e "1,${firstline}d" < "${0}" > "${gnuplotscript}"


################################################################################
## run gnuplot
/usr/bin/gnuplot -e "inputfile=\"${inputfile}\"" "${gnuplotscript}"
status=$?
if [[ ${status} -ne 0 ]] ; then
  echo "ERROR: gnuplot returned with exit status $?"
fi

################################################################################
## cleanup and exit
rm -f "${gnuplotscript}"
exit ${status}

#!/usr/bin/gnuplot
plot inputfile using 1:4 with linespoints
#... or whatever you want

My implementation is a bit more complex (e.g. replacing some magic tokens in the sed call, while I am already at it...), but I simplified this example for better understanding. You could also make it even simpler.... YMMV.


In the shell write

gnuplot -persist -e "plot filename1.dat,filename2.dat"

and consecutively the files you want. -persist is used to make the gnuplot screen stay as long as the user doesn't exit it manually.


Yet another way is this:

You have a gnuplot script named scriptname.gp:

#!/usr/bin/gnuplot -p
# This code is in the file 'scriptname.gp'
EPATH = $0
FILENAME = $1 

plot FILENAME

Now you can call the gnuplot script scriptname.gp by this convoluted peace of syntax:

echo "call \"scriptname.gp\" \"'.'\" \"'data.dat'\"" | gnuplot 

참고URL : https://stackoverflow.com/questions/12328603/how-to-pass-command-line-argument-to-gnuplot

반응형