[英]How do I accept user input on command line for python script instead of prompt
I have python code which asks user input. 我有要求用户输入的python代码。 (eg src = input('Enter Path to src: '). So when I run code through command prompt (eg python test.py) prompt appears 'Enter path to src:'. But I want to type everything in one line (eg python test.py c:\\users\\desktop\\test.py). What changes should I make? Thanks in advance
(例如src = input('输入src:的路径:')。因此,当我通过命令提示符(例如python test.py)运行代码时,会出现'Enter src:的路径。'。但是我想在一行中键入所有内容(例如python test.py c:\\ users \\ desktop \\ test.py),我应该进行哪些更改?
argparse or optparse are your friends. argparse或optparse是您的朋友。 Sample for optparse:
optparse的样本:
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
(options, args) = parser.parse_args()
and for argparse: 对于argparse:
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()
Replace src = input('Enter Path to src: ')
with: 将
src = input('Enter Path to src: ')
替换为:
import sys
src = sys.argv[1]
Ref: http://docs.python.org/2/library/sys.html 参考: http : //docs.python.org/2/library/sys.html
If your needs are more complex than you admit, you could use an argument-parsing library like optparse (deprecated since 2.7), argparse (new in 2.7 and 3.2) or getopt . 如果您的需求比您承认的要复杂,则可以使用参数解析库,例如optparse (从2.7开始不推荐使用), argparse (在2.7和3.2中新增)或getopt 。
Ref: Command Line Arguments In Python 参考: Python中的命令行参数
Here is an example of using argparse with required source and destination parameters: 这是将argparse与必需的源和目标参数一起使用的示例:
#! /usr/bin/python
import argparse
import shutil
parser = argparse.ArgumentParser(description="Copy a file")
parser.add_argument('src', metavar="SOURCE", help="Source filename")
parser.add_argument('dst', metavar="DESTINATION", help="Destination filename")
args = parser.parse_args()
shutil.copyfile(args.src, args.dst)
Run this program with -h
to see the help message. 使用
-h
运行该程序以查看帮助消息。
You can use sys.argv[1]
to get the first command line argument. 您可以使用
sys.argv[1]
获取第一个命令行参数。 If you want more arguments, you can reference them with sys.argv[2]
, etc. 如果需要更多参数,可以使用
sys.argv[2]
等进行引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.