互动鳕鱼中的Python

2024-06-11 11:26:17 发布

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

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

python
Loading pythonrc
>>>

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

^{pr2}$

当我以交互方式加载内容时,使用制表符完成(以及其他一些事情)会非常方便。在


Tags: 文件路径内容事情制表符时会loadingpr2
3条回答

从Pythondocumentation for ^{}

When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command, even when sys.stdin does not appear to be a terminal. The PYTHONSTARTUP file is not read.

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

正如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不意外地删除变量和内置函数的情况下执行此操作。在

显然,user module提供了这一点,但在python3.0中已被删除。这有点安全漏洞,取决于你的Python缸里有什么。。。在

相关问题 更多 >