简体   繁体   English

在python中通过命令行强制用户输入

[英]Force user input via command line in python

Say I'm running a script from the command line; 假设我从命令行运行脚本;

$python hello.py

This hello.py script will print 'Hello, Welcome!' 此hello.py脚本将显示“你好,欢迎光临!” And the in next line it prompts you to enter the name. 在下一行中,它提示您输入名称。 Example. 例。

$python hello.py

"Hello, welcome!"

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

Instead I want to parse my name while calling the script. 相反,我想在调用脚本时解析我的名字。

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

I know we can import sys and the name can be called via args[1] 我知道我们可以导入sys,并且可以通过args [1]来调用名称。

I was wondering if there is a way without modifying the code and changing the way we run the script via command line. 我想知道是否存在一种无需修改代码和更改我们通过命令行运行脚本的方式的方法。

You can pipe the answer to the script: 您可以将答案传递给脚本:

echo "John Smith" | python hello.py

or use a here-string: 或使用此处字符串:

python hello.py <<<"John Smith"

If you want to feed more than just one line of input, a here-doc is easier: 如果您要提供多行输入,那么这里文档更容易:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM