I have python code which asks user input. (e.g. src = input('Enter Path to src: '). So when I run code through command prompt (e.g. python test.py) prompt appears 'Enter path to src:'. But I want to type everything in one line (e.g. python test.py c:\users\desktop\test.py). What changes should I make? Thanks in advance
Asked
Active
Viewed 4,661 times
3 Answers
5
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()

hd1
- 33,938
- 5
- 80
- 91
-
so I have src = sys.argv[1] and dst = sys.argv[2] How can I put this in argparse or optparse? – user2661518 Aug 09 '13 at 22:31
-
@user2661518 You put them in as options. – hd1 Aug 11 '13 at 05:53
4
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.
-
-
@Rob so I have src = sys.argv[1] and dst = sys.argv[2] How can I put this in argparse or optparse? – user2661518 Aug 09 '13 at 22:39
1
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.

jh314
- 27,144
- 16
- 62
- 82