我只想将一个文件 pysome.py 用作
导入pysome
在控制台中
$ pysome
在后一种情况下,我不想调用一个函数, 在前一种情况下,我会这样做。
我有
entry_points={'console_scripts': ['pysome=pysome:main']}
在 setup.py 中。我试过了
如果 __name__ != '__main__: 一些乐趣()
但是 __name__ 结果是 pysome 即使作为脚本调用也是如此。
然后我尝试打包
安装程序.py pysome __init__.py __main__.py pysome.py
并将 setup.py 更改为
entry_points={'console_scripts': ['pysome=pysome.__main__:main']}
在 __init__.py 我有
从 .pysome 导入 * 一些乐趣()
在 __main__.py 中
从 .pysome 导入 *
但是当从控制台运行 pysome 时 some_fun() 仍然被调用。
在包裹的情况下,问题是: 如何在__main__.py中导入pysome而不导入__init__.py? 但是没有包的解决方案也很好。
使用 Python 3.6。
请您参考如下方法:
介绍垫片
我想到的最干净的解决方案是引入一个入口点填充函数,它将调用类型信息传递给主函数。有点像
# pysome.py
def main(called_from_cli=False):
if not called_from_cli:
print('imported')
else:
print('called from cli')
def _entrypoint_main():
main(called_from_cli=True)
在设置脚本中将入口点更改为 _entrypoint_main:
entry_points={'console_scripts': 'pysome=pysome:_entrypoint_main'}
照常从代码中调用 pysome.main()。如果你想解决调用 pysome.main(called_from_cli=True) 的情况,你可以引入一个全局标志而不是函数 arg,并在 shim 中打开和关闭它。
提取帧信息
您还可以检查调用程序模块 - 如果它是 pysome 脚本,那么 main() 是从 cli 调用的。但是,我认为 inspect 行为在不同的解释器上有所不同,不确定这里是否是这种情况。
import inspect
import os
def main():
frame = inspect.stack()[1]
module = inspect.getmodule(frame[0])
if module and os.path.basename(module.__file__) == 'pysome':
print('called from cli')
else:
print('imported')
pkg_resources检查(不推荐)
我猜你也可以检查 main() 在调用 main() 之前是否导入了 pkg_resources:
# pysome.py
import sys
def main():
if 'pkg_resources' in sys.modules.keys():
print('called from command line')
else:
print('called from code')
但是当然这只会在您不在代码中使用 pkg_resources 时起作用,因此请调用
import pkg_resources
import pysome
pysome.main()
将破坏支票。这会使事情变得非常脆弱,我不建议这样做。
