【问题标题】:User input from the command line [duplicate]来自命令行的用户输入[重复]
【发布时间】:2020-04-11 09:15:33
【问题描述】:

我必须制作一个像这样从命令行调用的程序

python3 hello.py <name>

我能够像这样完成它,但它仍然要求输入名称:

def hello(name: str):
    if name == None or name == '':
        return 'Hello, World!'
    else:
        return 'Hello, ' + name


    if __name__ == '__main__':
    print_hello(input("How can I call you?"))

【问题讨论】:

  • 这不使用命令行提供的参数,而是要求输入。

标签: python python-3.x bash command-line


【解决方案1】:

你可以使用sys.argvCheck the docs

import sys
print_hello(sys.argv[1])

【讨论】:

  • 已编辑,使用了错误的索引
  • 如果我想输入多个参数怎么办?我尝试使用“argv”作为参数,并使用具有“*args”参数的方法调用它,但它会引发错误,提示:TypeError: can only concatenate str (not "list") to str
  • sys.argv 返回一个列表,其中第一个元素是脚本的名称。您可以从 [1:] 迭代此列表并将其传递给方法。
猜你喜欢
  • 2013-02-25
  • 2013-04-08
  • 1970-01-01
  • 2013-12-12
  • 2018-11-30
  • 2015-06-03
  • 2015-09-05
  • 2014-03-29
  • 1970-01-01
相关资源
最近更新 更多