How to use arguments passed to a python script?

5

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

For example (Script):

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

Example call:

 my_name_is.php Wallace

The output will be:

  

My name is Wallace

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

    
asked by anonymous 15.02.2016 / 14:32

1 answer

6

According to this response from SOen , you can import the sys library, 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 is always the name of the script that is running.

For example:

 > args.py one two tree 

Return

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

If you want to return from the argument 1 on (lists start counting 0% with%), you can use zero to cut the first element of the argument list.

So:

print sys.argv[1:]

Return:

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

If you still want to use the slice variable without having to invoke it from the argv module, you can do this:

from sys import argv

print argv[1:]

I know there are other ways to do, just as Python has different libraries for similar purposes, I'll edit and add more later, I think the example would look like this:

import sys

print 'Meu nome é ', sys.argv[1]
    
15.02.2016 / 14:34