我想知道如何只运行一小部分代码而不运行所有以前的代码,这样的事情对我来说非常方便,因为我正在编写代码只是为了看看它是如何工作的,我在相同的 Python 文件,所以当我只想运行我最近编写的文件时,它也会运行所有以前的文件。
我只想运行突出显示的部分,而不是之前的所有行:
答案 0 :(得分:1)
您应该在函数中编写所有代码。 并在主函数中调用它。 例如:
# 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.
答案 1 :(得分:0)
定义/函数是最好的方法。
def afunc():
print('This is the function printed after the other function')
def func(): # Starts the definition
print('This is a function')
afunc()
func() # Runs the Code
答案 2 :(得分:0)
我没有专门使用 Pycharm,但我知道在许多其他 Python IDE(VS Code、Spyder、Jupyter)中,您可以将脚本分解为单元格并单独运行每个单元格。
对于 VS Code 和 Spyder,您可以通过包含以 #%%
开头的行来指定不同的单元格
这也将打开一个交互式 python shell,您可以在其中修改和重新运行每个部分或键入要运行的单独行