Nick
Nick

Reputation: 35

Getting Command line in Python

So I am working on this project where I take input from the user (a file name ) and then open and check for stuff. the file name is "cur" Now suppose the name of my file is kb.py (Its in python) If I run it on my terminal then first I will do: python kb.y and then there will a prompt and user will give the input. I'll do it this way:

A = raw_input("Enter File Name: ")
b = open(A, 'r+')

I dont want to do that. Instead i want to use it as a command for example: python kb.py cur and it will take it as an input and save to a variable which then will open it. I am confused how to get a input in the same command line.

Upvotes: 1

Views: 146

Answers (2)

Fredrik Pihl
Fredrik Pihl

Reputation: 45652

For simply stuff sys.argv[] is the way to go, for more complicated stuff, have a look at the argparse-module

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
   print "verbosity turned on"

output:

$ python prog.py --verbose
verbosity turned on
$ python prog.py --verbose 1
usage: prog.py [-h] [--verbose]
prog.py: error: unrecognized arguments: 1
$ python prog.py --help
usage: prog.py [-h] [--verbose]

optional arguments:
  -h, --help  show this help message and exit
  --verbose   increase output verbosity

Upvotes: 0

Óscar López
Óscar López

Reputation: 236004

Just use sys.argv, like this:

import sys

# this part executes when the script is run from the command line
if __name__ == '__main__':
    if len(sys.argv) != 2: # check for the correct number of arguments
        print 'usage: python kb.py cur'
    else:
        call_your_code(sys.argv[1]) # first command line argument

Note: sys.argv[0] is the script's name, and sys.argv[1] is the first command line argument. And so on, if there were more arguments.

Upvotes: 5

Related Questions