繁体   English   中英

如何在带有函数的VS Code中使用Python Interactive Window

[英]How to use Python Interactive Window in VS Code with functions

我是使用 python 交互式 window 的新手,我喜欢它,但它似乎在两次运行之间清除局部变量,所以如果我运行类似


def main():
    dates = '2012152'
    # %%
    print(dates)              # want to just run this

    # %%


if __name__ == '__main__':
    main()

# or even
main()

一下子一切正常,但是如果我只运行中间的单元格,我会收到“未定义日期”错误。 它在 function 之外工作,因为显然保存了一个全局变量:

dates = '2012152'
# %%
print(dates)             # this works if this cell is run

# %%

有没有办法在 function 中获得类似的行为? 如果不是,它对我来说似乎根本没有用(也许我的代码设计得很糟糕?)。

单元格是试验平面代码的好方法,但在嵌套在函数内部时它们会受到限制。 解决此问题的一种方法是使用常规内置python 调试器并在 function 中设置断点。

这是我用来在 function 中试验代码的过程:

  1. 在 function 处设置断点,在您要试验的代码之后开始调试。
  2. 对代码进行任何必要的更改。
  3. Select 您已更改并希望再次运行的行。 确保也包括所有缩进。
  4. 右键单击并 select Evaluate in Debug Console

这将允许您一次运行一行代码,查看结果,并在 go 进行时进行任何必要的调整。

通过将键盘快捷键绑定到此命令,可以进一步改进该过程。

Yes, print(dates) will not run as the dates variable isn't in scope, unless the function main is called and even then dates will be only in the local scope of the function, not in global scope.

所以要在function之外打印,需要先定义。

暂无
暂无

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

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