英文:
PyInstaller can have unexpected behavior if an `__init__.py ` parses the sys args
问题
我有一个名为dep
的包,在dep/__init__.py
中会解析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}")
我的主程序是:
# main.py
import dep
if __name__ == '__main__':
print("hello world")
如果我调用pyinstaller main.py
,PyInstaller会导入所有依赖项并运行所有的__init__.py
,这将导致"Got unexpected arg:",其中参数是PyInstaller\isolated\_child.py, 1300(用于PyInstaller IO的随机数), 1296(用于PyInstaller IO的随机数)
。
如何避免这个问题?
英文:
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?
答案1
得分: 1
当你导入一个包含在全局范围写的代码的模块时,该代码会在导入时立即运行。为了避免这种情况,只需将其封装在一个函数中。
dep.py
import sys
def check_args():
expected_args = ['--arg']
for arg in sys.argv:
if arg not in expected_args:
print(f"收到意外的参数: {arg}")
__main__.py
import dep
if __name__ == '__main__':
print("你好,世界")
dep.check_args()
英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论