0

I am writing code in Python that I should run with the command line and when I call the script i should give some arguments that I would use in the code. What can I use to achieve that?

To run the script it would be something like this:

python myscript.py s1 s2 s4

where s1, s2 and s4 would be the arguments that I would use in my code.

5 Answers 5

6

Quick dirty way

import sys
s1, s2, s4 = sys.argv[1:4]

(sys.argv[0] is the name of the script)

For more flexibility you can use the argparse module

Sign up to request clarification or add additional context in comments.

1 Comment

@leo: If you prefer argparse than I prefer Doug Hellman's tutorial on argparse.
4

Check out: http://docs.python.org/library/argparse.html

Python has a built in argument parser.

Comments

1

This is describe in the section entitled "Argument Passing" in the excellent Python Tutorial.

Comments

1

you can try:

import sys
print "file name:", sys.argv[0]
for i in range(1, len(sys.argv)):
    print "param:\t", i, sys.argv[i]

Comments

0

It's kind of a FAQ. The sys module has the facilities to access interpreter details. And one of the attribute sys.argv is list of command line arguments passed to the interpreter. So, when you access the sys.argv from a python program, which is executed by the interpreter, you will the program itself as the first argument and then rest of the arguments following it in the list starting from index 1.

$ cat 1.py 
import sys
print sys.argv

And when I execute it.

$python 1.py 0
['1.py', '0']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.