从终端执行python脚本时如何将参数传递给函数?

use*_*956 7 python command-line functions

我有一个名为 python 文件solution.py,我可以使用以下命令通过终端成功执行它:

chmod +x solution.py
python3 solution.py
Run Code Online (Sandbox Code Playgroud)

如果我有简单的打印短语等,这很好用。

如果我已经定义了一个函数solution.py并且我想直接从终端使用我想要的参数调用它,我该怎么办?如何将参数传递给函数调用?

Bud*_*hot 19

您也可以使用该sys模块。这是一个例子:

import sys

first_arg = sys.argv[1]
second_arg = sys.argv[2]

def greetings(word1=first_arg, word2=second_arg):
    print("{} {}".format(word1, word2))

if __name__ == "__main__":
    greetings()
    greetings("Bonjour", "monde")
Run Code Online (Sandbox Code Playgroud)

它具有您正在寻找的行为:

$ python parse_args.py Hello world
Hello world
Bonjour monde
Run Code Online (Sandbox Code Playgroud)


May*_*hux 2

Python 提供了不止一种解析参数的方法。最好的选择是使用该argparse模块,它有许多可以使用的功能。

因此,您必须解析代码中的参数,并尝试捕获并获取代码中的参数。

您不能只通过终端传递参数而不从代码中解析它们。