首页 > 解决方案 > 是否可以在当前终端中运行 Python 选择?

问题描述

VSCode我们有命令Python: Run Selection in Python terminal

是否可以在current终端中运行它而不是打开一个新终端?

在运行 Python 行之前,我需要在当前终端中运行一些脚本,这就是我要问的原因。

标签: pythonvisual-studio-code

解决方案


简短的回答是肯定的,这是可能的。但是你需要一个shell命令。我不认为按下Run Selection in Python terminal快捷方式会起作用。

例如,假设您在同一个目录中有两个脚本,命名为test1.pytest2.py具有各自的内容:

# test1.py 
print("This is the 1st script")

# test2.py 
print("This is the 2nd script")

要运行它们,您有以下选择(zsh在正确目录内的当前终端上运行这些命令):

1按顺序运行脚本,因为其中一个取决于前一个脚本的成功

% python test1.py && python test2.py

结果:

This is the 1st script
This is the 2nd script

2按顺序运行脚本,因为其中一个依赖于前一个脚本的失败

% python test1.py || python test2.py

出现错误时的结果test1.py

File "/Users/Documents/test/test1.py", line 2

^
SyntaxError: unexpected EOF while parsing
This is the 2nd script

3与后台进程同时运行脚本:

% python test1.py & python test2.py &

结果:

[1] 29290
[2] 29291
test % This is the 2nd script
This is the 1st script

[2]  + done       python test2.py
test % 
[1]  + done       python test1.py

您也可以将这些命令应用于不同数量的脚本,例如:

% python test1.py && python test2.py && python test3.py
% python test1.py || python test2.py && python test3.py

推荐阅读