如何在运行Python脚本(非交互式)时始终导入一个包?

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

How to always import a package when running Python script (non-interactive)?

问题

基本上,我想要复制PYTHONSTARTUP的行为,但在运行脚本时,即python app.py。我找到的答案涉及创建一个名为usercustomize.py的文件,并将其放置在python -m site指定的路径中。

这可以在执行其他脚本之前执行该脚本,但不会保留该脚本中的任何导入。我的目标是在可能的情况下始终使用Rich覆盖内置的打印函数。所以,我的当前PYTHONSTARTUP文件如下:

try:
    from rich import print, pretty
    pretty.install()
except ImportError:
    pass

如果我将上述内容放入usercustomize.py中,它会运行,但打印函数不会像我希望的那样被覆盖。这似乎是有意为之的设计,但是否有其他方法可以实现我想要的效果呢?

英文:

Basically I want to replicate the behavior of PYTHONSTARTUP but when running a script i.e. python app.py. The answers I've found for this involve creating a usercustomize.py file and putting it in the path specified by python -m site.

This works to execute the script before my other script but doesn't persist any imports in that script. My goal is to always override the builtin print function with Rich when possible. So my current PYTHONSTARTUP file looks like this:

try:
    from rich import print, pretty
    pretty.install()
except ImportError:
    pass

If I put the above in usercustomize.py, it runs but the print function isn't overridden like I want it to be. It seems that is by design, but is there any way of achieving what I want some other way?

答案1

得分: 2

你可能想要修改builtins模块的print属性。这会影响所有默认的print(...)调用。

try:
    from rich import print, pretty
    pretty.install()
    __import__('builtins').print = print
except ImportError:
    pass
英文:

You may want to modify the print attribute of the builtins module. This affects all default print(...) calls.

try:
    from rich import print, pretty
    pretty.install()
    __import__('builtins').print = print
except ImportError:
    pass

huangapple
  • 本文由 发表于 2023年6月19日 06:45:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502793.html
匿名

发表评论

匿名网友

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

确定