检测Python正在视觉工作室代码中运行
在某些情况下,如果在Visual Studio代码中运行,代码需要采取不同的行动。
有人知道检测Python代码在Visual Studio代码调试器中运行的最有效方法吗?
到目前为止,我能找到的最好的方法是使用:
import sys
if 'debugpy' in sys.modules:
print("Running in VS Code")
There are cases where code needs to act differently if running in Visual Studio Code.
Does anybody know the most efficient way to detect that the python code is running in the Visual Studio Code debugger?
So far, the best way I could find was using:
import sys
if 'debugpy' in sys.modules:
print("Running in VS Code")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在vscode上,环境变量
term_program
设置为“ vscode”,您可以通过:On vscode the environment variable
TERM_PROGRAM
is set to 'vscode', you can check it by:我认为解决此问题的最优雅方法只是在Vscode中设置运行任务,该任务运行Python脚本带有额外的命令行标志。
例如:
然后,如果您调用脚本
python myScript.py
python myScript.py -vscode
然后您只需在VSCODE中添加运行任务:
要运行代码,只需在运行任务中使用快捷方式
I think the most elegant way to solve this is just to set up a run task in vscode that runs the Python script with an extra command line flag.
for example:
then if you call the script
python myscript.py
if you call
python myscript.py --vscode
Then you can just add a run task in vscode:
To run your code, just use a shortcut for your run task
尽管我认为 @Eran的答案感觉最为简洁,但这是另一种方法:
它检测
debugpy
,如果另一个工具使用相同的debugpy
namesspace,则会防止误报。Although I think that @Eran's answer feels the most succinct, here is another method:
This detects
debugpy
and prevents false positive if another tool uses the samedebugpy
namespace.