从 Shell 脚本向 Python 传递参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39498702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing arguments to Python from Shell Script
提问by kskp
I wrote a small shell script that looks like this:
我写了一个小shell脚本,如下所示:
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:
我的python_code1.py
看起来像这样:
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:
现在,我的 shell 脚本中 echo $var1 的输出正是我想看到的:
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 _ _
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.
但是print data
python 代码中的输出只是1
. 即参数的第一个字母。
Why is this happening? I want to pass the entire string to the python code.
为什么会这样?我想将整个字符串传递给 python 代码。
回答by Dinesh Pundkar
If there is space in between argument and argument is not in quotes, then python consider as two different arguments.
如果参数之间有空格并且参数不在引号中,则python将其视为两个不同的参数。
That's why the output of print data in the python code is just 1.
这就是为什么python代码中打印数据的输出只有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.
因此,在您的 shell 脚本中,将 $var1 放在引号中。
Content of shell script(a.sh):
shell 脚本的内容(a.sh):
var1="Dinesh Pundkar"
python dsp.py "$var1"
Content of python code(dsp.py):
python代码的内容(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
回答by Kabard
Use Join and list slicing
使用连接和列表切片
import sys
data = ' '.join(sys.argv[1:])
print "In python code"
print data
print type(data)