从Shell脚本向Python传递参数 [英] Passing arguments to Python from Shell Script

查看:1047
本文介绍了从Shell脚本向Python传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小的shell脚本,如下所示:

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

我的python_code1.py看起来像这样:

import sys

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

现在,我的shell脚本中的echo $ var1的输出正是我想要看到的:

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 _ _

但是python代码中print data的输出只是1.即参数的第一个字母.

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

为什么会这样?我想将整个字符串传递给python代码.

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

推荐答案

如果参数之间存在空格,而参数不在引号中,则python认为是两个不同的参数.

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

这就是为什么python代码中的打印数据输出仅为1的原因.

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

检查以下输出.

[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 ~]#

因此,在您的shell脚本中,将$ var1放在引号中.

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

shell脚本的内容( a.sh ):

Content of shell script(a.sh):

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

python代码的内容( dsp.py ):

Content of python code(dsp.py):

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

输出:

[root@dsp-centos ~]# sh a.sh
In python code
Dinesh Pundkar

这篇关于从Shell脚本向Python传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆