-3

I want to pass a string (could be anything) with the program.

python argparsetest.py test_phrase
>>> You typed "test_phrase"

Edit: I realise this is a really simple question, I was planning on using argparse as a basis for adding further arguments at a later stage.

  • Have you tried the [doc](https://docs.python.org/2/howto/argparse.html)? Also, check [this question](http://stackoverflow.com/questions/7427101/dead-simple-argparse-example-wanted-1-argument-3-results) – fredtantini Sep 16 '14 at 10:33
  • *"Could anyone give me a hint where to start?"* is not an appropriate question for SO. – jonrsharpe Sep 16 '14 at 10:34

3 Answers3

1

Save the following as argparsetest.py and you're good to go. argv[n] returns the nth command-line argument.

from sys import argv

def main():
    print "You typed " + argv[1]

if __name__=='__main__':
    main()
Newb
  • 2,810
  • 3
  • 21
  • 35
1

Read the argparse documentation. It has an example implementing this exact scenario.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('test_phrase')
args = parser.parse_args()
print 'You typed "%s"' % args.test_phrase

Executing the script:

~/tmp/so$ python argparsetext.py example
You typed "example"
~/tmp/so$
Yoel
  • 9,144
  • 7
  • 42
  • 57
-1

I recommend docopts for option parsing. It lets you write the documentation first and generates a dictionary based on that. Maybe better for larger projects, as I am not sure what you are trying to do.

http://docopt.org

user3684792
  • 2,542
  • 2
  • 18
  • 23