You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在运行非交互式Python脚本时自动导入指定包?

问题

想要复刻PYTHONSTARTUP在运行脚本(如python app.py)时的行为,目前尝试把PYTHONSTARTUP里的代码放到python -m site指定路径下的usercustomize.py中,结果usercustomize.py确实会在目标脚本前执行,但里面导入的Rich库print函数没法在目标脚本中生效。

原PYTHONSTARTUP代码如下:

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

需要找其他方法实现Rich的print覆盖内置print的需求。

解决方案

1. 修改内置命名空间

在usercustomize.py里直接修改builtins模块的print属性,这样所有后续运行的代码都会用Rich的print:

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

builtins模块存着Python的内置函数,改它的print后,所有模块(包括你要运行的目标脚本)都会用替换后的函数。

2. 用环境变量指定前置脚本

通过PYTHONPATH和自定义脚本的方式,让目标脚本运行前先加载替换逻辑:

  • 新建rich_bootstrap.py文件,内容和上面修改builtins的代码一致
  • 运行目标脚本时执行:python -m rich_bootstrap app.py
  • 或者把该脚本所在目录加入PYTHONPATH,然后执行:python -c "import rich_bootstrap; import app"

3. 修改目标脚本的导入逻辑(侵入式)

如果能修改目标脚本,直接在脚本开头加这段代码:

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

这是最直接的方式,但需要修改每个要生效的脚本。


内容的提问来源于stack exchange,提问作者swigganicks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:35:07