从bash scrip向python传递参数

2024-05-23 18:35:54 发布

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

我一直在研究bash和{}脚本的混合脚本。bash脚本可以接收未知的count输入参数。例如:

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脚本?提前谢谢!在


Tags: 方法用户py脚本bash参数countsh
3条回答

除了上述切普纳的回答:

#!/bin/bash
tinify.py "$@"

在python脚本中,tinify.py公司名称:

^{pr2}$

列表arguments将包含传递给python脚本的参数(republiced removed as 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.sh中使用$@

#!/bin/bash
tinify.py "$@"

在Python脚本中消除重复项(从shell中过滤出来)会容易得多。(当然,这就产生了一个问题:您是否需要shell脚本。)

相关问题 更多 >