交互式代码中的pythonrc

时间:2010-11-09 17:23:47

标签: python shell

我的路径中有一个.pythonrc,当我运行python时会加载:

python
Loading pythonrc
>>>

问题是我执行文件时没有加载我的.pythonrc:

python -i script.py
>>>

当我以交互方式加载东西时,选项卡完成(以及其他一些事情)会非常方便。

4 个答案:

答案 0 :(得分:3)

来自Python documentation for -i

  

当脚本作为第一个参数传递或使用 -c 选项时,在执行脚本或命令后进入交互模式,即使sys.stdin似乎不是终奌站。未读取PYTHONSTARTUP文件。

我相信这样做是为了让脚本可以预测为所有用户运行,并且不依赖于用户特定的PYTHONSTARTUP文件中的任何内容。

答案 1 :(得分:1)

正如格雷格所指出的,-i行为方式有很好的理由。但是,我发现当我想要一个交互式会话时能够加载PYTHONSTARTUP非常有用。所以,这是我希望能够在PYTHONSTARTUP运行的脚本中激活-i时使用的代码。

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

请注意,这是相当hacky并且我永远不会这样做而不确保我的pythonrc不会意外地破坏变量和内置。

答案 2 :(得分:0)

显然user module提供了此功能,但已在Python 3.0中删除。这有点安全漏洞,取决于你的pythonrc中的内容......

答案 3 :(得分:0)

除了Chinmay Kanchi和Greg Hewgill的答案之外,我还想补充说IPython和BPython在这种情况下工作正常。也许是时候转换了吗? :)