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.
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
从Pythondocumentation for ^{} :
我相信这样做是为了让脚本可以预测地为所有用户运行,而不依赖于用户特定的PYTHONSTARTUP文件中的任何内容。在
正如Greg所指出的,有一个很好的理由来解释
-i
的行为方式。但是,当我想要一个交互式会话时,能够加载我的PYTHONSTARTUP
是非常有用的。所以,下面是我想在脚本中使用-i
运行PYTHONSTARTUP
时使用的代码。在请注意,这是相当粗糙的,我从不在不确保pythonrc不意外地删除变量和内置函数的情况下执行此操作。在
显然,user module提供了这一点,但在python3.0中已被删除。这有点安全漏洞,取决于你的Python缸里有什么。。。在
相关问题 更多 >
编程相关推荐