如何提示用户输入和读取命令行参数 [英] How to prompt for user input and read command-line arguments
问题描述
我如何拥有a)可以接受用户输入的Python脚本,以及如何使其成为b)如果从命令行运行则读入参数?
How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?
推荐答案
要阅读用户输入,您可以尝试 cmd
模块,可轻松创建迷你命令行解释器(带有帮助文本和自动完成功能)和 raw_input
( input
(对于Python 3+),用于从用户读取一行文本。
To read user input you can try the cmd
module for easily creating a mini-command line interpreter (with help texts and autocompletion) and raw_input
(input
for Python 3+) for reading a line of text from the user.
text = raw_input("prompt") # Python 2
text = input("prompt") # Python 3
命令行输入位于 sys.argv
中。在脚本中尝试以下操作:
Command line inputs are in sys.argv
. Try this in your script:
import sys
print (sys.argv)
有两个用于解析命令行选项的模块: (自python 2.7起已弃用,请使用 optparse
argparse
)和 getopt
。如果您只想向脚本输入文件,请注意 的功能fileinput
。
There are two modules for parsing command line options: (deprecated since Python 2.7, use optparse
argparse
instead) and getopt
. If you just want to input files to your script, behold the power of fileinput
.
Python库参考是您的朋友。
这篇关于如何提示用户输入和读取命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!