How to use the arguments passed to a python script?

Asked

Viewed 2,595 times

6

In scripts php, we can, when running from the command line, capture its values from the arguments passed through the variable $argv and its number through the variable $argc.

For example (Script):

echo 'My name is ', $argv[1]

Example called:

 my_name_is.php Wallace

The exit will be:

My name is Wallace

And in the Python? Is there any way to capture the arguments passed to a script, via command line?

1 answer

7


According to this response from Soen, you can import the library sys, some examples:

import sys

print "\n".join(sys.argv)

Another example with sys

import sys

for value in sys.argv:
    print value

Generally, the first argument of argv always is the name of the script being executed.

For example:

 > args.py one two tree 

Would return

['args.py', 'one', 'two', 'tree']

If you want to return from the argument 1 onwards (lists begin counting from 0 zero), can use the slice to cut the first element from the argument list.

Thus:

print sys.argv[1:]

Return:

['one', 'two', 'tree']

If you still want to use the variable argv without the need to invoke it from the module sys, you can do so:

from sys import argv

print argv[1:]

I know you have other ways of doing it, just like Python have different libraries for similar purposes, with time I will edit and add more, I believe that the example would look like this:

import sys

print 'Meu nome é ', sys.argv[1]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.