python - 将 bash 参数传递给 python 脚本

标签 python linux bash shell debian

我正在尝试创建一个 bash 脚本,它将自己的参数传递给 python 脚本。我希望它像这样工作。

如果我这样运行它:

script.sh latest

然后在 bash 脚本中运行带有“最新”参数的 python 脚本,如下所示:

python script.py latest

同样,如果 bash 脚本使用参数 123 运行,则 python 脚本如下:

python script.py 123

谁能帮我理解如何完成这个?

最佳答案

在这种情况下,诀窍是传递您拥有的任何参数(包括没有参数的情况),并保留原始命令行中存在的任何分组。

因此,您希望这三种情况有效:

script.sh                       # no args
script.sh how now               # some number
script.sh "how now" "brown cow" # args that need to stay quoted

因为 shell 是一种宏语言,所以并没有真正自然的方法来做到这一点,所以他们添加了一些神奇的语法,只是 DTRT。

#!/bin/sh

python script.py "$@"

关于python - 将 bash 参数传递给 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14340822/

相关文章:

python - 从 Django 模板标签的变量中分割字符串

linux - 使用 makefile 进行编译的多个 SRCDIR 文件夹

sql - 数据库中的标志 - 保持跟踪的明智方式

linux - 将中间管道拆分为变量

bash - 在 bash 中静音 docker rm 命令

python - 通过css为django模板加载图片

python - 按周划分 Pandas Dataframe

python - 如何迭代 Tensorflow 中的张量?

sql-server - 在 Linux 上的 SQL Server 中写入文件

linux - 使用 bash 脚本查找以太网地址