首页 > 解决方案 > Python 和 VS 代码问题

问题描述

VS Code 终端不会输出我的 Python 代码。

我不断得到这个:

PS C:\Users\danie\OneDrive\Documents\Exercise Files\Ch2> cd 'c:\Users\danie\OneDrive\Documents\Exercise Files\Ch2'; ${env:PYTHONIOENCODING}='UTF-8'; ${env:PYTHONUNBUFFERED}='1'; & 'C:/Python/Python37/Python.exe' 'c:\Users\danie\.vscode\extensions\ms-python.python-2019.5.18875\pythonFiles\ptvsd_launcher.py' '--default' '--client' '--host' 'localhost' '--port' '57829' 'c:\Users\danie\OneDrive\Documents\Exercise Files\Ch2\helloworld_start.py'

我已经按如下方式设置了 launch.JSON 文件

"version": "0.2.0",
"configurations": [
    {
        "name": "Python",
        "type": "python",
        "request": "launch",
        "stopOnEntry": true,
        "pythonPath": "${config:python.pythonPath}",
        "program": "${file}",
        "cwd": "",
        "env": {},
        "envFile": "${workspaceRoot}/.env",     
    }
]

这是我的代码:

def main():
    print("hello world")

    if __name__ == "__main__":
        main()

我只想打印出“hello world”,但似乎我在设置中遗漏了一些东西。

标签: pythonpython-3.x

解决方案


最后两行,你调用主函数的地方,被缩进了。这意味着它们是主要功能的一部分。

通过删除缩进,这两行将在您运行文件并按预期调用 main 函数时执行。看到这个

def main():
    print("hello world")

if __name__ == "__main__":
    main()

推荐阅读