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

查看:49
本文介绍了从 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 看起来像这样:

My python_code1.py looks like this:

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 _ ADPIN _ 4 准备_ _ 6 Northwest _ NOUN NNP _ 7 nn _ _ 7 阿肯色州_ 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.

推荐答案

如果argument之间有空格且argument不在引号中,则python认为是两个不同的arguments.

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 放在引号中.

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天全站免登陆