0

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

3 Answers 3

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()
Sign up to request clarification or add additional context in comments.

2 Comments

so I have src = sys.argv[1] and dst = sys.argv[2] How can I put this in argparse or optparse?
@user2661518 You put them in as options.
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.

2 Comments

+1 for completeness, in mentioning getopt, which I wasn't aware of.
@Rob so I have src = sys.argv[1] and dst = sys.argv[2] How can I put this in argparse or optparse?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.