如何提示用户输入和读取命令行参数 [英] How to prompt for user input and read command-line arguments

查看:90
本文介绍了如何提示用户输入和读取命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何拥有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)

有两个用于解析命令行选项的模块: optparse (自python 2.7起已弃用,请使用 argparse )和 getopt 。如果您只想向脚本输入文件,请注意 的功能fileinput

There are two modules for parsing command line options: optparse (deprecated since Python 2.7, use argparse instead) and getopt. If you just want to input files to your script, behold the power of fileinput.

Python库参考是您的朋友。

这篇关于如何提示用户输入和读取命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆