5

How do you accept/parse command line arguments for a py file that has no class? Here is what I have inside my file test.py:

import sys

if __name__ == '__main__':

How do I get the arguments when the file is executed via command line? I call it via:

python test.py <arg1>

and obviously want the value of "arg1".

6
  • I did and couldn't find much other than libraries that I don't want to import. Commented Oct 21, 2011 at 23:03
  • When you search for argv python. first link on Google is your answer Commented Oct 21, 2011 at 23:04
  • 5
    @EknathIyer That's all well and good, but what if you don't know to google for argv? This is perfectly appropriate. Commented Oct 21, 2011 at 23:07
  • 1
    How aboout: python commad line argument most results on the first page point to the right answer, with examples Commented Oct 21, 2011 at 23:21
  • 1
    @EknathIyer See meta.stackexchange.com/questions/5280/embrace-the-non-googlers. Google should lead here. This may not be a great question, but the fact that you can Google the answer if you know the right search terms doesn't mean it's not appropriate for SO. Commented Oct 21, 2011 at 23:32

2 Answers 2

9

Look no further than sys.argv, which is a list containing all arguments passed to the program.

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

2 Comments

Thank you sir, I figured it was something easy like this. For some reason I couldn't get a google search to provide me with this.
Remember "argv". That's standard computer speak for the arguments passed to any program. Historically it is short for "argument vector", a vector being mostly equivalent to what Python calls a list.
5
try:
    arg = sys.argv[1]
except IndexError:
    print "No argument specified."
    sys.exit(1)

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.