【问题标题】:VS Code How to make terminal run Python functions like IDLE?VS Code 如何让终端运行 IDLE 等 Python 函数?
【发布时间】:2022-06-18 08:25:53
【问题描述】:

抱歉,如果这已经解决,但我无法找到解决方案。我正在尝试像在 IDLE 中一样运行我的 python 文件。我记得在以前的设备中,我以某种方式更改了设置,因此我能够从正在运行的 python 文件中输入终端函数,它会运行该函数。

例子:

def main ():

    def function_2 ():
        print ('Value of x at start of the function: ', x)
        x = x + 10
        print ('Value of x at end of the function: ', x)

    x = 5
    print ('Value of x in main before calling function: ', x)
    function_2()
    print ('Value of x in main before calling function: ', x)

在 IDLE 中,我会运行 python 文件,然后在空闲终端中运行 main(),它就会运行。我也想做同样的事情,但使用 VS Code。任何帮助,将不胜感激。非常感谢。

【问题讨论】:

  • 从 IDLE 编辑器运行文件时,IDLE 运行它的方式与使用 python -i path/to/file 从命令行相同。 -i 表示在运行文件并将输出打印到 Python Shell 后,在交互式 shell 中打印交互式提示。除非 VS 代码以某种方式做同样的事情,否则没有地方可以输入诸如 main() 之类的 python 语句。

标签: python visual-studio-code python-idle


【解决方案1】:

试试这个

def main ():

    def function_2 ():
        print ('Value of x at start of the function: ', x)
        x = x + 10
        print ('Value of x at end of the function: ', x)

    x = 5
    print ('Value of x in main before calling function: ', x)
    function_2()
    print ('Value of x in main before calling function: ', x)

main()

【讨论】:

  • 那行得通,但如果我想通过在终端示例中运行 main() 来再次运行它,我希望能够再次运行它:我有 3 个函数,每个函数都有不同的问题解决方案为什么我可以不像 IDLE 那样在 vscode 终端中运行 function1()、function2() 或 function3()?
【解决方案2】:

添加这个

"python.defaultInterpreterPath": "python",
"python.terminal.launchArgs": ["-i"],

settings.json,你可以用Ctrl+Shift+P然后>Preferences: Open Settings (JSON)打开它

这会在打开的终端上运行命令,因此您每次都必须关闭 python 终端。

我还没有想出如何做得更好。所以不要认为这已经解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 2022-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    相关资源
    最近更新 更多