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?
我如何拥有a)可以接受用户输入的Python脚本以及如何创建它b)如果从命令行运行,则读入参数?
12 个解决方案
#1
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.
要读取用户输入,您可以尝试使用cmd模块轻松创建一个迷你命令行解释器(带有帮助文本和自动完成)和raw_input(用于Python 3+的输入),以便从用户读取一行文本。
text = raw_input("prompt") # Python 2text = input("prompt") # Python 3
Command line inputs are in sys.argv
. Try this in your script:
命令行输入在sys.argv中。在你的脚本中尝试这个:
import sysprint (sys.argv)
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
.
解析命令行选项有两个模块:optparse(自Python 2.7以来不推荐使用,而是使用argparse)和getopt。如果您只想将文件输入脚本,请注意fileinput的强大功能。
The Python library reference is your friend.
Python库参考是你的朋友。
#2
var = raw_input("Please enter something: ")print "you entered", var
Or for Python 3:
或者对于Python 3:
var = input("Please enter something: ")print("You entered: " + var)
#3
raw_input
is no longer available in Python 3.x. But raw_input
was renamed input
, so the same functionality exists.
Python 3.x中不再提供raw_input。但是raw_input被重命名为输入,因此存在相同的功能。
input_var = input("Enter something: ")print ("you entered " + input_var)
变更的文件
#4
The best way to process command line arguments is the argparse
module.
处理命令行参数的最佳方法是argparse模块。
Use raw_input()
to get user input. If you import the readline module
your users will have line editing and history.
使用raw_input()获取用户输入。如果您导入readline模块,您的用户将拥有行编辑和历史记录。
#5
Careful not to use the input
function, unless you know what you're doing. Unlike raw_input
, input
will accept any python expression, so it's kinda like eval
小心不要使用输入功能,除非你知道你在做什么。与raw_input不同,input将接受任何python表达式,因此它有点像eval
#6
This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.
这个简单的程序可以帮助您了解如何从命令行提供用户输入,并显示有关传递无效参数的帮助。
import argparseimport systry: parser = argparse.ArgumentParser() parser.add_argument("square", help="display a square of a given number", type=int) args = parser.parse_args() #print the square of user input from cmd line. print args.square**2 #print all the sys argument passed from cmd line including the program name. print sys.argv #print the second argument passed from cmd line; Note it starts from ZERO print sys.argv[1]except: e = sys.exc_info()[0] print e
1) To find the square root of 5
1)找到5的平方根
C:\Users\Desktop>python -i emp.py 525['emp.py', '5']5
2) Passing invalid argument other than number
2)传递除数字以外的无效参数
C:\Users\bgh37516\Desktop>python -i emp.py fiveusage: emp.py [-h] squareemp.py: error: argument square: invalid int value: 'five'<type 'exceptions.SystemExit'>
#7
Use 'raw_input' for input from a console/terminal.
使用'raw_input'从控制台/终端输入。
if you just want a command line argument like a file name or something e.g.
如果你只是想要一个命令行参数,比如文件名或者某些东西,例如
$ python my_prog.py file_name.txt
then you can use sys.argv...
那么你可以使用sys.argv ...
import sysprint sys.argv
sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be "file_name.txt"
sys.argv是一个列表,其中0是程序名,因此在上面的例子中,sys.argv [1]将是“file_name.txt”
If you want to have full on command line options use the optparse module.
如果要使用完整的命令行选项,请使用optparse模块。
Pev
#8
If you are running Python <2.7, you need optparse, which as the doc explains will create an interface to the command line arguments that are called when your application is run.
如果您运行的是Python <2.7,则需要optparse,正如文档所解释的那样,它将创建一个接口,用于运行应用程序时调用的命令行参数。
However, in Python ≥2.7, optparse has been deprecated, and was replaced with the argparse as shown above. A quick example from the docs...
但是,在Python≥2.7中,optparse已被弃用,并被替换为argparse,如上所示。来自文档的快速示例......
The following code is a Python program that takes a list of integers and produces either the sum or the max:
以下代码是一个Python程序,它获取整数列表并生成总和或最大值:
import argparseparser = argparse.ArgumentParser(description='Process some integers.')parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')args = parser.parse_args()print args.accumulate(args.integers)
#9
As of Python 3.2 2.7, there is now argparse for processing command line arguments.
从Python 3.2 2.7开始,现在有用于处理命令行参数的argparse。
#10
If it's a 3.x version then just simply use:
如果它是3.x版本,那么只需使用:
variantname = input()
For example, you want to input 8:
例如,您要输入8:
x = input()8
x will equal 8 but it's going to be a string except if you define it otherwise.
x将等于8但它将是一个字符串,除非你另外定义它。
So you can use the convert command, like:
所以你可以使用convert命令,如:
a = int(x) * 1.1343print(round(a, 2)) # '9.07'9.07
#11
In Python 2:
在Python 2中:
data = raw_input('Enter something: ')print data
In Python 3:
在Python 3中:
data = input('Enter something: ')print(data)
#12
import sixif six.PY2: input = raw_inputprint(input("What's your name? "))
#1
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.
要读取用户输入,您可以尝试使用cmd模块轻松创建一个迷你命令行解释器(带有帮助文本和自动完成)和raw_input(用于Python 3+的输入),以便从用户读取一行文本。
text = raw_input("prompt") # Python 2text = input("prompt") # Python 3
Command line inputs are in sys.argv
. Try this in your script:
命令行输入在sys.argv中。在你的脚本中尝试这个:
import sysprint (sys.argv)
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
.
解析命令行选项有两个模块:optparse(自Python 2.7以来不推荐使用,而是使用argparse)和getopt。如果您只想将文件输入脚本,请注意fileinput的强大功能。
The Python library reference is your friend.
Python库参考是你的朋友。
#2
var = raw_input("Please enter something: ")print "you entered", var
Or for Python 3:
或者对于Python 3:
var = input("Please enter something: ")print("You entered: " + var)
#3
raw_input
is no longer available in Python 3.x. But raw_input
was renamed input
, so the same functionality exists.
Python 3.x中不再提供raw_input。但是raw_input被重命名为输入,因此存在相同的功能。
input_var = input("Enter something: ")print ("you entered " + input_var)
变更的文件
#4
The best way to process command line arguments is the argparse
module.
处理命令行参数的最佳方法是argparse模块。
Use raw_input()
to get user input. If you import the readline module
your users will have line editing and history.
使用raw_input()获取用户输入。如果您导入readline模块,您的用户将拥有行编辑和历史记录。
#5
Careful not to use the input
function, unless you know what you're doing. Unlike raw_input
, input
will accept any python expression, so it's kinda like eval
小心不要使用输入功能,除非你知道你在做什么。与raw_input不同,input将接受任何python表达式,因此它有点像eval
#6
This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.
这个简单的程序可以帮助您了解如何从命令行提供用户输入,并显示有关传递无效参数的帮助。
import argparseimport systry: parser = argparse.ArgumentParser() parser.add_argument("square", help="display a square of a given number", type=int) args = parser.parse_args() #print the square of user input from cmd line. print args.square**2 #print all the sys argument passed from cmd line including the program name. print sys.argv #print the second argument passed from cmd line; Note it starts from ZERO print sys.argv[1]except: e = sys.exc_info()[0] print e
1) To find the square root of 5
1)找到5的平方根
C:\Users\Desktop>python -i emp.py 525['emp.py', '5']5
2) Passing invalid argument other than number
2)传递除数字以外的无效参数
C:\Users\bgh37516\Desktop>python -i emp.py fiveusage: emp.py [-h] squareemp.py: error: argument square: invalid int value: 'five'<type 'exceptions.SystemExit'>
#7
Use 'raw_input' for input from a console/terminal.
使用'raw_input'从控制台/终端输入。
if you just want a command line argument like a file name or something e.g.
如果你只是想要一个命令行参数,比如文件名或者某些东西,例如
$ python my_prog.py file_name.txt
then you can use sys.argv...
那么你可以使用sys.argv ...
import sysprint sys.argv
sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be "file_name.txt"
sys.argv是一个列表,其中0是程序名,因此在上面的例子中,sys.argv [1]将是“file_name.txt”
If you want to have full on command line options use the optparse module.
如果要使用完整的命令行选项,请使用optparse模块。
Pev
#8
If you are running Python <2.7, you need optparse, which as the doc explains will create an interface to the command line arguments that are called when your application is run.
如果您运行的是Python <2.7,则需要optparse,正如文档所解释的那样,它将创建一个接口,用于运行应用程序时调用的命令行参数。
However, in Python ≥2.7, optparse has been deprecated, and was replaced with the argparse as shown above. A quick example from the docs...
但是,在Python≥2.7中,optparse已被弃用,并被替换为argparse,如上所示。来自文档的快速示例......
The following code is a Python program that takes a list of integers and produces either the sum or the max:
以下代码是一个Python程序,它获取整数列表并生成总和或最大值:
import argparseparser = argparse.ArgumentParser(description='Process some integers.')parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')args = parser.parse_args()print args.accumulate(args.integers)
#9
As of Python 3.2 2.7, there is now argparse for processing command line arguments.
从Python 3.2 2.7开始,现在有用于处理命令行参数的argparse。
#10
If it's a 3.x version then just simply use:
如果它是3.x版本,那么只需使用:
variantname = input()
For example, you want to input 8:
例如,您要输入8:
x = input()8
x will equal 8 but it's going to be a string except if you define it otherwise.
x将等于8但它将是一个字符串,除非你另外定义它。
So you can use the convert command, like:
所以你可以使用convert命令,如:
a = int(x) * 1.1343print(round(a, 2)) # '9.07'9.07
#11
In Python 2:
在Python 2中:
data = raw_input('Enter something: ')print data
In Python 3:
在Python 3中:
data = input('Enter something: ')print(data)
#12
import sixif six.PY2: input = raw_inputprint(input("What's your name? "))