Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to Python from Shell Script

I wrote a small shell script that looks like this:

cd models/syntaxnet
var1=$(jq --raw-output '.["avl_text"]' | syntaxnet/demo.sh)
echo $var1
python /home/sree/python_code1.py $var1

My python_code1.py looks like this:

import sys

data = sys.argv[1]
print "In python code"
print data
print type(data)

Now, the output of echo $var1 in my shell script is exactly what I wanted to see:

1 Check _ VERB VB _ 0 ROOT _ _ 2 out _ PRT RP _ 1 prt _ _ 3 this _ DET DT _ 4 det _ _ 4 video _ NOUN NN _ 1 dobj _ _ 5 about _ ADP IN _ 4 prep _ _ 6 Northwest _ NOUN NNP _ 7 nn _ _ 7 Arkansas _ NOUN NNP _ 5 pobj _ _ 8 - _ . , _ 7 punct _ _ 9 https _ X ADD _ 7 appos _ _

But the output of print data in the python code is just 1. i.e. the first letter of the argument.

Why is this happening? I want to pass the entire string to the python code.

like image 235
kskp Avatar asked Sep 14 '16 19:09

kskp


2 Answers

If there is space in between argument and argument is not in quotes, then python consider as two different arguments.

That's why the output of print data in the python code is just 1.

Check the below output.

[root@dsp-centos ~]# python dsp.py Dinesh Pundkar
In python code
Dinesh
[root@dsp-centos ~]# python dsp.py "Dinesh Pundkar"
In python code
Dinesh Pundkar
[root@dsp-centos ~]#

So, in your shell script, put $var1 in quotes.

Content of shell script(a.sh):

var1="Dinesh Pundkar"
python dsp.py "$var1"

Content of python code(dsp.py):

import sys
data = sys.argv[1]
print "In python code"
print data

Output:

[root@dsp-centos ~]# sh a.sh
In python code
Dinesh Pundkar
like image 154
Dinesh Pundkar Avatar answered Oct 02 '22 15:10

Dinesh Pundkar


Use Join and list slicing

import sys
data = ' '.join(sys.argv[1:])
print "In python code"
print data
print type(data)
like image 44
Kabard Avatar answered Oct 02 '22 16:10

Kabard