【问题标题】:Force user input via command line in python在python中通过命令行强制用户输入
【发布时间】:2019-03-07 00:36:10
【问题描述】:

假设我正在从命令行运行脚本;

$python hello.py

这个 hello.py 脚本将打印“你好,欢迎!”在下一行中,它会提示您输入名称。例子。

$python hello.py

"Hello, welcome!"

What is you name?:<here you enter the name and press enter for the program to continue>

相反,我想在调用脚本时解析我的名字。

$python hello.py <do something to parse the name>

我知道我们可以导入 sys 并且可以通过 args[1] 调用名称

我想知道是否有一种方法无需修改代码并更改我们通过命令行运行脚本的方式。

【问题讨论】:

    标签: python parsing input command-line args


    【解决方案1】:

    您可以将答案传递给脚本:

    echo "John Smith" | python hello.py
    

    或使用此处的字符串:

    python hello.py <<<"John Smith"
    

    如果您想提供多于一行的输入,here-doc 会更容易:

    python hello.py <<EOF
    Answer to first question
    Answer to second question
    and so on
    EOF
    

    【讨论】:

    • 如果我想要一个 bash 脚本调用 hello.py 并做同样的事情,我该怎么做?
    • 没什么区别,你把我写的放到脚本里就行了。
    • 我不明白。说我的 bash 脚本是 cmd = "python hello.py"; res=${cmd};, 如何在此处更改 res 以包含 echo "John Smith |"?
    • res=$($cmd &lt;&lt;&lt;"John Smith")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    相关资源
    最近更新 更多