在 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 脚本并且您甚至不知道它正在这样做……您想要的是 usercustomize
或 sitecustomize
,如 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 thesite-packages
directory.After this, an attempt is made to import a module named
usercustomize
, which can perform arbitrary user-specific customizations, ifENABLE_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/