问题:用户输入和命令行参数

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


回答 0

要读取用户输入,您可以尝试使用cmd模块轻松创建一个迷你命令行解释器(带有帮助文本和自动完成功能),以及raw_inputinput用于Python 3+)从用户读取一行文本的模块。

text = raw_input("prompt")  # Python 2
text = input("prompt")  # Python 3

命令行输入在中sys.argv。在脚本中尝试:

import sys
print (sys.argv)

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

Python库参考是你的朋友。

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

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

import sys
print (sys.argv)

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.

The Python library reference is your friend.


回答 1

var = raw_input("Please enter something: ")
print "you entered", var

或对于Python 3:

var = input("Please enter something: ")
print("You entered: " + var)
var = raw_input("Please enter something: ")
print "you entered", var

Or for Python 3:

var = input("Please enter something: ")
print("You entered: " + var)

回答 2

raw_input在Python 3.x中不再可用。但是raw_input已被重命名input,因此存在相同的功能。

input_var = input("Enter something: ")
print ("you entered " + input_var) 

变更文件

raw_input is no longer available in Python 3.x. But raw_input was renamed input, so the same functionality exists.

input_var = input("Enter something: ")
print ("you entered " + input_var) 

Documentation of the change


回答 3

处理命令行参数的最佳方法是argparse模块。

使用raw_input()来获取用户输入。如果导入,readline module您的用户将具有行编辑和历史记录。

The best way to process command line arguments is the argparse module.

Use raw_input() to get user input. If you import the readline module your users will have line editing and history.


回答 4

input除非您知道自己在做什么,否则请小心不要使用该功能。与不同raw_inputinput它将接受任何python表达式,因此有点像eval

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


回答 5

这个简单的程序可以帮助您了解如何从命令行输入用户输入以及如何显示有关传递无效参数的帮助。

import argparse
import sys

try:
     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)求5的平方根

C:\Users\Desktop>python -i emp.py 5
25
['emp.py', '5']
5

2)传递数字以外的无效参数

C:\Users\bgh37516\Desktop>python -i emp.py five
usage: emp.py [-h] square
emp.py: error: argument square: invalid int value: 'five'
<type 'exceptions.SystemExit'>

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 argparse
import sys

try:
     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

C:\Users\Desktop>python -i emp.py 5
25
['emp.py', '5']
5

2) Passing invalid argument other than number

C:\Users\bgh37516\Desktop>python -i emp.py five
usage: emp.py [-h] square
emp.py: error: argument square: invalid int value: 'five'
<type 'exceptions.SystemExit'>

回答 6

使用“ raw_input”从控制台/终端输入。

如果您只想使用命令行参数,例如文件名或其他名称,例如

$ python my_prog.py file_name.txt

那么你可以使用sys.argv …

import sys
print sys.argv

sys.argv是一个列表,其中0是程序名称,因此在上面的示例中sys.argv [1]将是“ file_name.txt”

如果要使用命令行选项完整选项,请使用optparse模块。

佩夫

Use ‘raw_input’ for input from a console/terminal.

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…

import sys
print 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”

If you want to have full on command line options use the optparse module.

Pev


回答 7

如果您运行的是Python <2.7,则需要optparse,如文档所述,它将创建一个接口,以连接在运行应用程序时调用的命令行参数。

但是,在python≥2.7中,不建议使用optparse,并如上所述将其替换为argparse。来自文档的快速示例…

以下代码是一个Python程序,它接收一个整数列表并产生总和或最大值:

import argparse

parser = 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)

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.

However, in Python ≥2.7, optparse has been deprecated, and was replaced with the argparse as shown above. A quick example from the docs…

The following code is a Python program that takes a list of integers and produces either the sum or the max:

import argparse

parser = 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)

回答 8

从Python开始 3.22.7中,现在有用于处理命令行参数的argparse

As of Python 3.2 2.7, there is now argparse for processing command line arguments.


回答 9

如果是3.x版本,则只需使用:

variantname = input()

例如,您要输入8:

x = input()
8

x等于8,但是它将是一个字符串,除非您另行定义。

因此,您可以使用convert命令,例如:

a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07

If it’s a 3.x version then just simply use:

variantname = input()

For example, you want to input 8:

x = input()
8

x will equal 8 but it’s going to be a string except if you define it otherwise.

So you can use the convert command, like:

a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07

回答 10

在Python 2中:

data = raw_input('Enter something: ')
print data

在Python 3中:

data = input('Enter something: ')
print(data)

In Python 2:

data = raw_input('Enter something: ')
print data

In Python 3:

data = input('Enter something: ')
print(data)

回答 11

import six

if six.PY2:
    input = raw_input

print(input("What's your name? "))
import six

if six.PY2:
    input = raw_input

print(input("What's your name? "))

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。