简体   繁体   English

PyCharm:在 Python 控制台中执行

[英]PyCharm: execute in Python console

I'm working on a Python project in PyCharm.我正在 PyCharm 中开发一个 Python 项目。 For one file I would like to test parts of the code using the Python console.对于一个文件,我想使用 Python 控制台测试部分代码。 Problem is that the code contains a main method (used for debugging and execution) like this:问题是代码包含一个 main 方法(用于调试和执行),如下所示:

if __name__ == "__main__":
    print("with main")
else:
    print("no main")

When I execute that code in the Python Console (using context menu of PyCharm) then the first part of the if will be executed.当我在 Python 控制台(使用 PyCharm 的上下文菜单)中执行该代码时,将执行 if 的第一部分。 I was expecting the else-part since I'm not starting the script using a Run-configuration.我期待其他部分,因为我没有使用运行配置启动脚本。

Maybe you can help me how to do that.也许你可以帮助我如何做到这一点。

Create file like not_main_start.py with only one line import main.py (I guess this is your main file).创建像not_main_start.py这样的文件,只有一行import main.py (我猜这是你的主文件)。 Run then this file.然后运行这个文件。 Output should show no main .输出不应显示no main __name__ would be name __main__ only if you call this file directly. __name__将是 name __main__仅当您直接调用此文件时。 If you use it as module then it will have name of the module.如果您将其用作模块,那么它将具有模块的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM