简体   繁体   中英

How do I accept user input on command line for python script instead of prompt

I have python code which asks user input. (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

argparse or optparse are your friends. Sample for 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:

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:

import sys
src = sys.argv[1]

Ref: 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 .

Ref: Command Line Arguments In Python


Here is an example of using argparse with required source and destination parameters:

#! /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.

You can use sys.argv[1] to get the first command line argument. If you want more arguments, you can reference them with sys.argv[2] , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM