Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sys.argv scoping rules

Tags:

python

I just noticed sys.argv is visible in a imported script.

A.py

import sys
print("A")
print(sys.argv)
import B

B.py

import sys
print("B")
print(sys.argv)

Yields

>> python A.py --foo bar
>> A
>> ['path/to/A.py', '--foo', 'bar']
>> B
>> ['path/to/A.py', '--foo', 'bar']

This is nice since now I don't have to do the argument parsing in the main script (aka. manage.py).

The question is: can I rely on this behavior? Are there cases where this will not work?

like image 545
RickyA Avatar asked Apr 02 '14 11:04

RickyA


People also ask

How does Sys argv work in Python?

sys. argv is the list of commandline arguments passed to the Python program. argv represents all the items that come along via the command line input, it's basically an array holding the command line arguments of our program. Don't forget that the counting starts at zero (0) not one (1).

Can we set SYS argv in Python?

Passing command line arguments in Python 3.To use it, we first need to import sys module (import sys). The first argument, sys. argv[0], is always the name of the script and sys. argv[1] is the first argument passed to the script.

How do I pass SYS argv in Python?

sys. argv is a list in Python, which contains the command-line arguments passed to the script. With the len(sys. argv) function you can count the number of arguments.

What is the type of each element in SYS argv in Python?

What is the type of each element in sys. argv? Explanation: It is a list of strings.


1 Answers

Module attributes, like sys.argv are objects. It does not matter from which module you access them, they are the same object.

That also means if one module modifies sys.argv, then that change will also affect any other module that accesses sys.argv.


A tip regarding coding style:

Although it is possible to access sys.argv from two different modules, I wouldn't recommend it, and here's why.

I like scripts that can also double as modules. This gives you the greatest flexibility in reusing code. sys.argv is only meaningful when the code is called as a script. In order for code to be useful as a module, the code should not depend on looking up values in sys.argv.

Therefore, I would recommend parsing sys.argv once in the main calling script:

if __name__ == '__main__':
    import argparse
    def parse_args():
        ... # argparse uses  sys.argv

    args = parse_args()

and then passing the values in args to functions as needed.

Thus, everything outside of the if __name__ == 'main__' statement need not depend on sys.argv, and can thus be used through simple function calls or module imports.

like image 140
unutbu Avatar answered Sep 22 '22 19:09

unutbu