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)