从shell脚本向python程序插入参数

2024-05-08 01:45:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从shell脚本执行python程序,这样python程序中的print命令就可以从另一个程序中读取了。 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程序应该得到parametrs$1和$2,但它不将它们识别为parametrs,而是将-c和它后面的命令作为parametrs。你知道吗

例如:在我的另一个项目中获取流程输入流对我来说不起作用。唯一可行的方法是使用-c选项和命令exec系统标准读取()'. 你知道吗

谢谢你。你知道吗


Tags: 命令ltechogt程序脚本bashif
2条回答

按照你写的方式应该很好用。在精简版中,我得到的是:

(bash)test.sh脚本:

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

(Python)测试.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模块也非常有用。这允许您将自定义标志添加到程序中(从用户的角度来看,使用它也更方便)。你知道吗

相关问题 更多 >