繁体   English   中英

从Shell脚本向Python程序插入参数

[英]Insert parameters to python program from shell script

我需要从shell脚本执行python程序,以便暴露python程序中的打印命令,以便从另一个程序读取。 shell脚本:

#!/bin/bash

if [ $# -lt 1 ] || [ $# -gt 2 ];then
    echo "Usage: $0 APK <duration in seconds>"
    exit 1;
fi

printf "$(python '/root/Desktop/DroidBox_4.1.1/scripts/droidbox.py' $1 $2 -c 'import sys; exec sys.stdin.read()')"

我的python程序应该获取参数$ 1和$ 2,但它不能将它们识别为参数,而是将-c和其后的命令作为参数。

对于诸如以下的答案:在我的其他项目中获取流程输入流对我而言不起作用。 似乎可行的唯一方法是使用-c选项和命令“ exec sys.stdin.read()”。

谢谢。

就像您编写代码一样,它应该可以很好地工作。 在精简版中,这是我得到的:

(bash) test.sh脚本:

#!/bin/bash    
python /tmp/test.py $1 $2

(python)test.py脚本:

import sys
print "in python"
print sys.argv

最后是一个shell session

smassey@hacklabs:/tmp $ ./test.sh hello world
in python
['/tmp/test.py', 'hello', 'world']

如您所见,bash脚本调用python脚本,该脚本将值打印到stdout因此它们与其他指向stdout内容一样公开:

smassey@hacklabs:/tmp $ ./test.sh hello world | grep python | tr 'a-z' 'A-Z'
IN PYTHON

argparse模块也非常有用。 这使您可以向程序中添加自定义标志(从用户的角度来看,也更加方便使用)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM