pythonrc in interactive code

2019-04-13 02:26发布

问题:

I have a .pythonrc in my path, which gets loaded when I run python:

python
Loading pythonrc
>>>

The problem is that my .pythonrc is not loaded when I execute files:

python -i script.py
>>>

It would be very handy to have tab completion (and a few other things) when I load things interactively.

回答1:

From the Python documentation for -i:

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.

I believe this is done so that scripts run predictably for all users, and do not depend on anything in a user's particular PYTHONSTARTUP file.



回答2:

As Greg has noted, there is a very good reason why -i behaves the way it does. However, I do find it pretty useful to be able to have my PYTHONSTARTUP loaded when I want an interactive session. So, here's the code I use when I want to be able to have PYTHONSTARTUP active in a script run with -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

Note that this is fairly hacky and I never do this without ensuring that my pythonrc isn't accidentally clobbering variables and builtins.



回答3:

Apparently the user module provides this, but has been removed in Python 3.0. It is a bit of a security hole, depending what's in your pythonrc...



回答4:

In addition to Chinmay Kanchi and Greg Hewgill's answers, I'd like to add that IPython and BPython work fine in this case. Perhaps it's time for you to switch? :)



标签: python shell