如何在每次启动Python时运行Python命令

2024-04-16 06:48:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何在每次启动python解释器时运行一个或多个命令。在

有没有一种方法可以像.bashrc或.profile文件那样在python中实现这一点呢?在


Tags: 文件方法命令profile解释器bashrc
1条回答
网友
1楼 · 发布于 2024-04-16 06:48:40

您可以设置一个环境变量PYTHONSTARTUP指向一个文件,该文件包含您希望在启动所有python解释器时运行的命令。在

更多信息可以在python文档中找到:https://docs.python.org/2/tutorial/interpreter.html#the-interactive-startup-file

如果要从当前目录运行其他启动文件或从脚本运行此全局启动文件,也可以使用以下有用信息:

If you want to read an additional start-up file from the current directory, you can program this in the global start-up file using code like if os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py'). If you want to use the startup file in a script, you must do this explicitly in the script:

import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
    execfile(filename)

相关问题 更多 >