首页 > 解决方案 > 如何只运行文件中的特定代码行?

问题描述

我想知道如何只运行一小部分代码而不运行所有以前的代码,这样的事情对我来说非常方便,因为我编写代码只是为了看看它是如何工作的,我在同一个 Python 中这样做文件,所以当我只想运行我最近编写的文件时,它也会运行所有以前的文件。

我只想运行突出显示的部分,而不是前面的所有行:

在此处输入图像描述

标签: python

解决方案


您应该将所有代码都放在函数中。并在主函数中调用它。例如:

# Import necessary libraries.

# Define your functions from the top
def Foo():
    print('foo')

def Bar():
    print('bar')

if __name__ == '__main__':
    # Run your code from here, call the needed functions.
    Foo()
    Bar()
    # If you don't want to run Bar(), simply comment it.

推荐阅读