Search code examples
pyinstaller

PyInstaller can have unexpected behavior if an `__init__.py ` parses the sys args


I have a package dep, where the dep/__init__.py will parse the sys.argv

# dep/__init__.py
import sys

expected_args = ['--arg']

for arg in sys.argv:
    if arg not in expected_args:
        print(f"Got unexpected arg: {arg}")

my MAIN is

# main.py
import dep
if __name__ == '__main__':
    print("hello world")

If I call pyinstaller main.py, PyInstaller will import all its dependencies and run all __init__.py, this will result in "Got unexpected arg:"

where the args are PyInstaller\isolated\_child.py, 1300(a random number for PyInstaller IO), 1296(a random number for PyInstaller IO)

How to avoid this issue?


Solution

  • When you import a module that has code written in the global scope, the code is run immediately upon import. In order to avoid this, just wrap it in a function.

    dep.py

    import sys
    
    def check_args():
        expected_args = ['--arg']
        for arg in sys.argv:
            if arg not in expected_args:
                print(f"Got unexpected arg: {arg}")
    

    __main__.py

    import dep
    if __name__ == '__main__':
        print("hello world")
        dep.check_args()