May-29-2024, 07:58 PM
(This post was last modified: May-29-2024, 09:16 PM by Gribouillis.)
You could start the interpreter with the -i option
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__']))
« We can solve any problem by introducing an extra level of indirection »