Check python interactive mode in sitecustomize
I have a MOTD-type message which prints on invocation o开发者_开发问答f the interpreter. Currently this is printed up in sitecustomize. I'd like to suppress the message if the interpreter is not in interactive mode; unfortunately all of the checks in
Tell if Python is in interactive mode do not work in sitecustomize. (sys.argv
, sys.ps1
, __main__.__file__
are not populated.) Are there checks which work in sitecustomize?
JAB got me looking at the code and I ultimately came up with this:
import ctypes
import getopt
ctypes.pythonapi.Py_GetArgcArgv.restype = None
ctypes.pythonapi.Py_GetArgcArgv.argtypes = [
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.POINTER(ctypes.c_char_p))]
count = ctypes.c_int()
args = ctypes.pointer(ctypes.c_char_p())
ctypes.pythonapi.Py_GetArgcArgv(ctypes.byref(count), ctypes.byref(args))
argc = count.value
argv = [args[i] for i in range(count.value)]
if argc > 1:
interactive = False
opts, args = getopt.getopt(argv[1:], 'i')
for o, a in opts:
if o == '-i':
interactive = True
else:
interactive = True
Kinda ugly (and for Py3k the c_char_p need to be c_wchar_p) but does the job.
Perhaps this idea for checking interpreter interactivity that utilizes the inspect
module and checks stack frames might be of some use to you:
http://mail.python.org/pipermail/pythonmac-sig/2002-February/005054.html
You could also try looking directly at the source of pydoc.help()
, which the above-linked code snippets were inspired by.
Just realized that you could simply utilize a file containing your interactive prompt with the PYTHONSTARTUP
environment variable. The commands in the file pointed to by PYTHONSTARTUP
will only be executed when the interpreter is run interactively.
http://docs.python.org/tutorial/interpreter.html#the-interactive-startup-file
If you don't want to set the environment variable outside of Python, you might be able to set the variable to the desired file in sitecustomize.py
, but when I tried looking into it to find the loading order it took me right back to the link from the first part of my answer.
Checking the sys.flags is a cleaner way.
>>> import sys
>>> sys.flags.interactive
1
Note, the IDLE is also interactive in its nature, but the flag is not set. I would do below:
>>> if sys.flags.interactive or sys.modules.has_key('idlelib'):
>>> pass # do stuff specific to interactive.
精彩评论