交互代码中的pythonrc
我在我的路径里有一个 .pythonrc 文件,这个文件在我运行 Python 时会被加载:
python
Loading pythonrc
>>>
但问题是,当我执行文件时,我的 .pythonrc 文件并不会被加载:
python -i script.py
>>>
如果在交互式加载时能有自动补全(还有一些其他功能)就太方便了。
4 个回答
0
显然,user模块提供了这个功能,但在Python 3.0中被移除了。这个模块有点安全隐患,具体要看你的pythonrc文件里有什么内容...
0
正如Greg提到的,-i
的行为是有很好的原因的。不过,我觉得在需要交互式会话时,能够加载我的PYTHONSTARTUP
是非常有用的。所以,这里是我在用-i
运行脚本时,想要让PYTHONSTARTUP
生效时使用的代码。
if __name__ == '__main__':
#do normal stuff
#and at the end of the file:
import sys
if sys.flags.interactive==1:
import os
myPythonPath = os.environ['PYTHONSTARTUP'].split(os.sep)
sys.path.append(os.sep.join(myPythonPath[:-1]))
pythonrcName = ''.join(myPythonPath[-1].split('.')[:-1]) #the filename minus the trailing extension, if the extension exists
pythonrc = __import__(pythonrcName)
for attr in dir(pythonrc):
__builtins__.__dict__[attr] = getattr(pythonrc, attr)
sys.path.remove(os.sep.join(myPythonPath[:-1]))
del sys, os, pythonrc
需要注意的是,这种做法有点“黑科技”,我绝对不会在没有确认我的pythonrc不会意外覆盖变量和内置函数的情况下使用它。
4
来自Python的文档关于-i
选项的说明:
当你把一个脚本作为第一个参数传入,或者使用-c选项时,执行完脚本或命令后会进入交互模式,即使
sys.stdin
看起来不是一个终端。PYTHONSTARTUP文件不会被读取。
我认为这样做是为了让所有用户运行脚本时的行为是一致的,不会受到用户特定的PYTHONSTARTUP文件的影响。