英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论