using command line arguments

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • peruron
    New Member
    • Aug 2007
    • 11

    using command line arguments

    Hello again!

    I've been trying to make my code more generic, and one of the things I want to do is to use a given file name, which can change (in the command line) instead of using a specific name.
    My code looks like:

    def func1
    bla bla bla

    def func2
    bla bla bla

    main code.

    My questions are:
    Should I name the main code "main" in order to use sys.argv?
    What is the exact syntax of argv? If you want to put the first argument (as in 1, not 0) in a string variable, how do I do that?
    Should I import anything, and if so, where should I locate the "import..." line? before all the functions, before the main code etc?

    I have tried a python websites, but I can't find answers to those questions.


    Thanks
  • ilikepython
    Recognized Expert Contributor
    • Feb 2007
    • 844

    #2
    Originally posted by peruron
    Hello again!

    I've been trying to make my code more generic, and one of the things I want to do is to use a given file name, which can change (in the command line) instead of using a specific name.
    My code looks like:

    def func1
    bla bla bla

    def func2
    bla bla bla

    main code.

    My questions are:
    Should I name the main code "main" in order to use sys.argv?
    What is the exact syntax of argv? If you want to put the first argument (as in 1, not 0) in a string variable, how do I do that?
    Should I import anything, and if so, where should I locate the "import..." line? before all the functions, before the main code etc?

    I have tried a python websites, but I can't find answers to those questions.


    Thanks
    There is no need for main (this isn't C) ;). argv is part of the system module so to use it, do something like this:
    [CODE=python]import sys
    print sys.argv[0] # program name
    print sys.argv[1:] # command line arguements; if any[/CODE]
    sys.argv is basically a list of what you typed at the command line:
    Code:
    C:\Documents and Settings\UserName> myprogram.py these are some command line arguments 1 3
    sys.argv will be:
    [code=python]
    ["myprogram. py", "these", "are", "some", "command", "line", "arguments" , 1, 3]
    [/code]

    Comment

    Working...