Python Forum
initializing interactive mode
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
initializing interactive mode
#4
(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.

Notice I exec the code in the namespace of the __main__ module because I want to make an initialized variable x available at the interpreter prompt.
« We can solve any problem by introducing an extra level of indirection »
Reply


Messages In This Thread
initializing interactive mode - by Skaperen - May-29-2024, 07:20 PM
RE: initializing interactive mode - by Gribouillis - May-29-2024, 07:58 PM
RE: initializing interactive mode - by Skaperen - May-29-2024, 11:48 PM
RE: initializing interactive mode - by Gribouillis - May-30-2024, 06:25 AM
RE: initializing interactive mode - by Skaperen - Jun-02-2024, 03:29 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020