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

user2661518
  • 2,677
  • 9
  • 42
  • 79

3 Answers3

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

Community
  • 1
  • 1
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
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