Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python command line arguments in main, skip script name

This is my script

def main(argv):
    if len(sys.argv)>1:
        for x in sys.argv:
            build(x)

if __name__ == "__main__":
    main(sys.argv)

so from the command line I write python myscript.py commandlineargument

I want it to skip myscript.py and simply run commandlineargument through commandlineargument(n)

so I understand that my for loop doesn't account for this, but how do I make it do that?

like image 554
CQM Avatar asked Sep 25 '13 23:09

CQM


People also ask

Can we pass arguments in main () in Python?

Command Line Args Python Code The main() above begins with a CS106A standard line args = sys. argv[1:] which sets up a list named args to contain the command line arg strings. This line works and you can always use it.

Can we pass arguments to Python script?

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys. argv ) will store all the information in the command line entry and can be accessed inside the Python script. Python's getopt module can also be used to parse named arguments.

How do I pass a command line ARGument in idle?

IDLE now has a GUI way to add arguments to sys. argv! Under the 'Run' menu header select 'Run... Customized' or just Shift+F5... A dialog will appear and that's it!


1 Answers

Since sys.argv is a list, you can use slicing sys.argv[1:]:

def main(argv):
    for x in argv[1:]:
        build(x)

if __name__ == "__main__":
    main(sys.argv)

But, if you can only have one script parameter, just get it by index: sys.argv[1]. But, you should check if the length of sys.argv is more than 1 and throw an error if it doesn't, for example:

def main(argv):
    if len(argv) == 1:
        print "Not enough arguments"
        return
    else:
        build(argv[1])

if __name__ == "__main__":
    main(sys.argv)
like image 120
alecxe Avatar answered Sep 19 '22 20:09

alecxe