May-29-2024, 07:20 PM
i recall reading that interactive mode could be initialized with either a command line option or the file .init.py instead. i tried the latter but it seems to have no effect. is that the correct name to do this?
Output:λ echo 'x = 1009' > spam.py
λ
λ python -i spam.py
>>> x
1009
>>>
Second way, using an environment variableOutput:λ PYTHONSTARTUP=spam.py python
Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x
1009
>>>
Note that you cannot combine the two ways because with the PYTHONSTARTUP is not read if you start python with -iOutput:λ echo 'y = 9000' > eggs.py
λ PYTHONSTARTUP=spam.py python -i eggs.py
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> y
9000
>>>
Here is a third untested way, if you don't want to define PYTHONSTARTUP (I never define permanently python-related environment variables). In file usercustomize.py write this# in usercustomize.py import sys if hasattr(sys, 'ps1'): # we are in interactive mode with open('spam.py') as ifh: exec(ifh.read(), vars(sys.modules['__main__']))
(May-29-2024, 07:58 PM)Gribouillis Wrote: [ -> ]Here is a third untested way, if you don't want to define PYTHONSTARTUP (I never define permanently python-related environment variables). In file usercustomize.py write this
# in usercustomize.py import sys if hasattr(sys, 'ps1'): # we are in interactive mode with open('spam.py') as ifh: exec(ifh.read(), vars(sys.modules['__main__']))
(May-29-2024, 11:48 PM)Skaperen Wrote: [ -> ]can file usercustomize.py be put in the user's home directory?usercustomize.py needs to be importable, that is to say on the python path. Typically, the right place would be the directory returned by
site.getusersitepackages()
.(May-29-2024, 11:48 PM)Skaperen Wrote: [ -> ]could i just put some other code in place of open+exec lines, under the test for interactive, to do what i want to happen in interactive?I tested the above code and it doesn't work! It seems that
sys.ps1
is set after usercustomize
is imported. Here is an alternative that does what you're asking.# in usercustomize.py import sys import __main__ if (not sys.argv[0]) or sys.flags.interactive: # sys.argv[0] is '' in interactive mode # sys.flags.interactive is True if -i flag is present print('We are in interactive mode') exec('x = 3.14', vars(__main__))The interactivity test may not work on all python interpreters (such as embedded interpreters in IDEs or files compiled to .exe etc). At least it works well in the python interpreter installed in Linux.
PYTHONSTARTUP=/home/phil/.init.py
environment variable, file /home/phil/.init.py
does preset a lot of variables including x. it also imports a few things i usually use in interactive mode.