的Python:用户输入命令行参数 [英] Python: user input and commandline arguments

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

问题描述

我如何有一个Python脚本,可以接受用户输入(假设这是可能的),如何让它在参数读取如果从命令行运行?

How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?

推荐答案

要读取用户输入您可以尝试的用于轻松创建一个小型的命令行间preTER(与帮助文字和自动完成)的CMD模块并的 的raw_input少花哨的东西(只是阅读文本从用户线)。

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 for less fancy stuff (just reading a line of text from the user).

命令行输入在sys.argv中。在你的脚本试试这个对于Python 2:

Command line inputs are in sys.argv. Try this in your script for Python 2:

import sys
print sys.argv

对于Python 3:

For Python 3:

import sys
print(sys.argv)

由于印刷已经从一个关键词改为在Python 2成一个函数调用在Python 3。

Since print has changed from a keyword in Python 2 into a function call in Python 3.

有两个模块用于解析命令行选项: optparse 和<一个HREF =htt​​p://docs.python.org/2/library/getopt.html相对=nofollow> getopt的。如果你只是想输入文件到你的脚本,谁知的FileInput 的权力。

There are two modules for parsing command line options: optparse and getopt. If you just want to input files to your script, behold the power of fileinput.

借助 Python库参考是你的朋友

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

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