我如何有一个Python脚本,可以接受用户输入,我如何使它读参数,如果从命令行运行?
当前回答
这个简单的程序帮助您理解如何从命令行提供用户输入,以及如何在传递无效参数时显示帮助。
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)传递除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'>
其他回答
注意不要使用输入函数,除非你知道你在做什么。与raw_input不同,input将接受任何python表达式,因此它有点像eval
这个简单的程序帮助您理解如何从命令行提供用户输入,以及如何在传递无效参数时显示帮助。
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)传递除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'>
import six
if six.PY2:
input = raw_input
print(input("What's your name? "))
在Python 2中:
data = raw_input('Enter something: ')
print data
在Python 3中:
data = input('Enter something: ')
print(data)
如果是3。X版本然后只需简单地使用:
variantname = input()
例如,你想输入8:
x = input()
8
X将等于8,但它将是一个字符串除非你另有定义。
所以你可以使用convert命令,像这样:
a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录