运行 python 已导入模块的脚本

Run python script with module/ modules already imported

我已经尝试了几乎所有的解决方案来做到这一点,但事实是我不能 运行 已经导入模块的 python 脚本。

这是我的模块代码 cls.py:

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

下面给出了在cmd中打开python的代码:

@echo off
python
pause

我需要的是在导入了模块cls的命令提示符下打开python。另外,当我尝试 python -m <module> 方式时,它没有显示任何错误,但程序结束了。

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

我想你要找的是 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

因此只需在批处理文件中使用 python -i cls.py。这将导入您的 Python 文件并停留在 Python 解释器提示符中。然后你可以调用 cls() 因为它已经导入了。

或者,您可以在批处理文件中设置环境变量 PYTHONSTARTUP

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.