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?
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.
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.
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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With