PyInstaller如果一个`__init__.py`文件解析了sys参数,可能会出现意外行为。

huangapple go评论67阅读模式
英文:

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

问题

我有一个名为dep的包,在dep/__init__.py中会解析sys.argv

  1. # dep/__init__.py
  2. import sys
  3. expected_args = ['--arg']
  4. for arg in sys.argv:
  5. if arg not in expected_args:
  6. print(f"Got unexpected arg: {arg}")

我的主程序是:

  1. # main.py
  2. import dep
  3. if __name__ == '__main__':
  4. 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

  1. # dep/__init__.py
  2. import sys
  3. expected_args = ['--arg']
  4. for arg in sys.argv:
  5. if arg not in expected_args:
  6. print(f"Got unexpected arg: {arg}")

my MAIN is

  1. # main.py
  2. import dep
  3. if __name__ == '__main__':
  4. 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

  1. import sys
  2. def check_args():
  3. expected_args = ['--arg']
  4. for arg in sys.argv:
  5. if arg not in expected_args:
  6. print(f"收到意外的参数: {arg}")

__main__.py

  1. import dep
  2. if __name__ == '__main__':
  3. print("你好,世界")
  4. 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

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

__main__.py

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

huangapple
  • 本文由 发表于 2023年5月22日 13:57:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76303363.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定