You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过终端及Python os模块调用编辑器打开.py文件

How to Open a .py File in VS Code via Python's os Module (Instead of Running It)

Alright, let's sort this out for you. When you use os.system('python3 test.py'), you're telling your system to execute the Python script directly—no wonder it's not opening in VS Code! The trick is to call the VS Code executable itself, rather than the Python interpreter. Here's how to do it across different operating systems:

For macOS or Linux

The terminal command to open a file in VS Code is code filename.py. Translating that to Python's os module is straightforward:

import os
os.system('code test.py')

Quick note: If your terminal doesn't recognize the code command, you need to add VS Code to your system PATH. Open VS Code, bring up the command palette (press Cmd+Shift+P on macOS, Ctrl+Shift+P on Linux), search for "Shell Command: Install 'code' command in PATH", and run that option. It'll set everything up automatically.

For Windows

On Windows, the approach depends on whether you added VS Code to your PATH during installation:

  1. If VS Code is in your PATH: Same as macOS/Linux—use the code command:
    import os
    os.system('code test.py')
    
  2. If code isn't recognized: You'll need to use the full file path to the VS Code executable. For most default installations, that path is C:\Program Files\Microsoft VS Code\Code.exe. Here's how to use it:
    import os
    os.system('"C:\\Program Files\\Microsoft VS Code\\Code.exe" test.py')
    

Pro tip: To find the exact path if yours is different, right-click the VS Code shortcut, go to Properties, and copy the path from the "Target" field. Just remember to escape backslashes with another backslash (like \\) in your Python string.

A More Robust Alternative: Use subprocess Instead of os.system

While os.system works, the subprocess module is the recommended way to run system commands in Python these days—it gives you better control over the process, error handling, and output. Here's how to use it for opening your .py file:

macOS/Linux

import subprocess
subprocess.run(['code', 'test.py'])

Windows

import subprocess
# If VS Code is in PATH
subprocess.run(['code', 'test.py'])
# Or with full path
subprocess.run(['C:\\Program Files\\Microsoft VS Code\\Code.exe', 'test.py'])

The core idea here is simple: instead of invoking python3 to run your script, you're invoking VS Code's executable to open it as an editable file in the IDE. That's the key difference that fixes your original issue.

内容的提问来源于stack exchange,提问作者user18292031

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:12:49