Computer >> Computer tutorials >  >> Programming >> Python

How to import Python modules by default at the time of program starts?


Use the environment variable PYTHONSTARTUP. From the official documentation:

If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session.

So, just create a python script with the import statements and point the environment variable to it. For instructions on how to create environment variables on your OS see: https://www.java.com/en/download/help/path.xml. Use the variable name as PYTHONSTARTUP instead of PATH.

Having said that, remember that 'Explicit is always better than implicit', so don't rely on this behavior for production scripts. Also the more imports you add slower your python startup time will become.