python - 有没有办法在python启动时始终执行脚本? (类似于 R 中的 site.profile)

标签 python startup

在 R 编程语言中,有一个 site.profile 文件,它定义了 R 进程在启动时执行的一些代码。 Python 中有类似的功能吗?

编辑:澄清一下,如果用户从命令行调用 python,那么应该执行此脚本,而且如果 python 从另一个进程生成(例如,如果用户的脚本使用子进程生成另一个 python)。

最佳答案

如果您只希望在交互式 session 中使用此功能(而不是每次使用 python myscript.py./myscript 运行脚本或使用python -m mymodule), 你要的是环境变量PYTHONSTARTUP :

If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session…

如果你希望这永远发生,当然,你需要在一些适当的全局位置设置这个环境变量——例如,你在大多数 *nix 平台上的 shell 配置文件,或者你的 shell 配置文件和你在 macOS 上的 launchd 配置文件,或 Windows 上控制面板的相应部分(相应部分随几乎每个新版本的 Windows 而变化,但名称中通常带有“系统”)。

如果您希望这对所有 用户发生,而不仅仅是当前用户……关于如何设置系统范围环境变量的详细信息更多是特定于平台的,但除此之外的想法是一样。


如果您希望在每个 Python session 中发生这种情况,即使其他程序正在运行 Python 脚本并且您甚至不知道它正在这样做……您想要的是 usercustomizesitecustomize,如 site 中所述文档:

This module is automatically imported during initialization. The automatic import can be suppressed using the interpreter’s -S option.

After these path manipulations, an attempt is made to import a module named sitecustomize, which can perform arbitrary site-specific customizations. It is typically created by a system administrator in the site-packages directory.

After this, an attempt is made to import a module named usercustomize, which can perform arbitrary user-specific customizations, if ENABLE_USER_SITE is true. This file is intended to be created in the user site-packages directory (see below), which is part of sys.path unless disabled by -s

因此,您想找到一个合适的地方来覆盖它。首先试试这个:

python3 -m site

然后,如果这没有给你 sys.path(可能只在相当老的 Python 上,但以防万一......),也这样做:

python3 -c 'import sys; print('\n'.join(sys.path))'

如果您希望此自定义仅对当前用户发生,您需要在 python3 列出的 USER_SITE 目录中创建一个 usercustomize.py 文件 - m 站点。如果该目录不存在,请创建它。

如果您希望它对所有用户都发生,您需要在 sys.path 目录之一中创建一个 sitecustomize.py 文件。问题是可能已经有一个了。例如,大多数 Linux 发行版的内置 Python 包都有自己的 sitecustomize 模块。如果有,python3 -c 'import sitecustomize; print(sitecustomize.__file__) 会告诉你它在哪里。然后,您可以编辑或复制它,编辑该副本,并将该副本放置在 sys.path 中比原始文件更早的位置。作为一般规则,/usr/local 可能比 /usr 好,而 site-packages 可能比 dist- packages 可能比其他任何东西都好。

关于python - 有没有办法在python启动时始终执行脚本? (类似于 R 中的 site.profile),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51071691/

相关文章:

python - nltk 的 Tornado 多进程崩溃

Python 以可能由其小数位数预先确定的最小步长递增 float

ubuntu - 脚本在while循环中运行时计算机不会关闭

c - 如何知道应用程序的启动点

python - 我试图在两次之间循环,从 8 :00 to 17:00 for every 15 mins

python - 为什么 NaN 被视为 float ?

python - 将整个 csv 转换为 json 文件- python

linux - 在 Buffallo NAS (Optware) 上自动启动 noip2

C# - 在系统启动时最小化到托盘

java - 有没有办法只在 Tomcat/Wildfly/Glassfish 启动时运行方法/类?