[英]I want to pass multiple arguments to python script from bash script
[英]Pass arguments to python from bash script
我一直在研究bash
和python
脚本的脚本混合。 bash脚本可以接收未知的计数输入参数。 例如 :
tinify.sh test1.jpg test2.jpg test3.jpg .....
在bash收到all之后,它将这些参数传递给tinify.py
。 现在我已经有两种方法可以做到这一点。
在bash
循环并调用python tinify.py testx.jpg
换句话说, python tinify test1.jpg
然后是python tinify test2.jpg
, python tinify test3.jpg
将所有参数传递给tinify.py
然后在python
循环
但是有一个问题,我想过滤相同的参数,例如,如果用户输入tinify.sh test1.jpg test1.jpg test1.jpg
,我只想要tinify.sh test1.jpg
。所以我认为第二种方式更容易因为python可能很方便。
如何将所有参数传递给python脚本? 提前致谢!
你在tinify.sh
使用$@
#!/bin/bash
tinify.py "$@"
消除Python脚本中要从shell中过滤掉的重复项要容易得多。 (当然,这引发了一个问题,你是否需要一个shell脚本。)
除了Chepner的答案之外:
#!/bin/bash
tinify.py "$@"
在python脚本中,tinify.py:
from sys import argv
inputArgs = sys.argv[1:]
def remove_duplicates(l):
return list(set(l))
arguments=remove_duplicates(inputArgs)
list arguments
将包含传递给python脚本的参数(复制已删除,因为set
不能包含python中的重复值)。
python程序可以使用sys.argv
接受任意数量的命令行参数 - 只记得sys.argv[0]
是脚本的名称,实际参数包含在sys.argv[1:]
$ cat test_args.py
from sys import argv
prog_name = argv[0]
print('Program name:', prog_name)
for arg in argv[1:]:
print(arg)
$ python test_args.py a b 'c d'
Program name: test_args.py
a
b
c d
$
请注意,必须根据shell语法引用包含空格的参数。
你的文件tinify.py
应该从以下开始(如果你有两个参数):
import sys
arg1, arg2 = sys.argv[1], sys.argv[2]
sys.argv[0]
是脚本本身的名称。 你当然可以循环遍历sys.argv
。 就个人而言,我喜欢将所有参数作为json对象传递,所以之后我做了json.loads()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.