Home > Blockchain >  Run python script with module/ modules already imported
Run python script with module/ modules already imported

Time:11-13

I have tried nearly all solutions in my mind to do this, but the fact is I can't run a python script with modules imported already.

Here's my code for the module cls.py:

import os
def cls(): 
     os.system('cls')

Given below is the code for opening python in cmd:

@echo off
python
pause

What I need is to open the python in the command prompt with the module cls imported. Also, when I try python -m <module> way, it doesn't show any errors, but the program ends.

Any help would be greatly appreciated and thanks in advance. Saw this question related to mine, but it is not my problem: Run python script that imports modules with batch file

CodePudding user response:

I think what you'r looking for is the interactive mode:

-i
When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command

So just use python -i cls.py in your batch file. This would import your Python file and stay in the Python interpreter prompt. You could then just call cls() because it's already imported.

Alternatively, you could set the environment variable PYTHONSTARTUP in your batch file:

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.

  • Related