Linux 将 bash 参数传递给 python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14340822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:40:26  来源:igfitidea点击:

Pass bash argument to python script

pythonlinuxbashshelldebian

提问by Jimmy

I am trying to create a bash script which passes its own argument onto a python script. I want it to work like this.

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

If I run it as this:

如果我这样运行它:

script.sh latest

Then within the bash script it runs a python script with the "latest" argument like this:

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

python script.py latest

Likewise if the bash script is run with the argument 123 then the python script as such:

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

python script.py 123

Can anyone help me understand how to accomplish this please?

谁能帮我理解如何做到这一点?

采纳答案by DigitalRoss

In this case the trick is to pass however many arguments you have, including the case where there are none, and to preserve any grouping that existed on the original command line.

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

So, you want these three cases to work:

因此,您希望这三种情况起作用:

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

There isn't really a natural way to do this because the shell is a macro language, so they've added some magic syntax that will just DTRT.

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

#!/bin/sh

python script.py "$@"

回答by Grambot

In bash, arguments passed to the script are accessed with the $#notation (# being a number. Using $# exactly like that should give you the number of args passed). So if you wanted to pass arguments:

在 bash 中,传递给脚本的参数是用$#符号访问的(# 是一个数字。完全使用 $# 应该给你传递的参数数量)。所以如果你想传递参数:

Calling the script:

调用脚本:

`#script.sh argument`

Within the script:

在脚本中:

python script.py ""

回答by wewa

In the pythonscript script.pyuse getopt.getopt(args, options[, long_options])to get the arguments.

在 pythonscript 中script.py用于getopt.getopt(args, options[, long_options])获取参数。

Example:

例子:

import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        else:
            assert False, "unhandled option"
    # ...

if __name__ == "__main__":
    main()

回答by Uriel Fernando Sandoval

A very goo buit-in parser is argparse. Yo can use it as follows:

一个非常粘的内置解析器是 argparse。您可以按如下方式使用它:

  import argparse

  parser = argparse.ArgumentParser(description='Process some integers.')
  parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
  parser.add_argument('--sum', dest='accumulate', action='store_const',
                     const=sum, default=max,
                   help='sum the integers (default: find the max)')

  args = parser.parse_args()
  print(args.accumulate(args.integers))