Search code examples
pythonvisual-studio-codesubprocesspopen

How can I open visual studio code from Python?


I am trying to write a simple script, which will be opening Visual Studio Code whenever I execute it.

This is my code so far:

import subprocess
subprocess.Popen(['C:/Users/path/Visual Studio Code'])

as a parameter to Popen I have entered the path to Visual Studio Code. Despite that I get the following error when I execute the script:

Traceback (most recent call last):
  File "02.environment_set_up.py", line 3, in <module>
    subprocess.Popen(['Visual Studio Code'])
  File "C:\Users\andri\Anaconda3\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\Users\andri\Anaconda3\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden
PS C:\Users\andri\PythonProjects\Automate-The-Boring-Stuff> py 02.environment_set_up.py
Traceback (most recent call last):
  File "02.environment_set_up.py", line 3, in <module>
    subprocess.Popen(['C:/Users/andri/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Visual Studio Code'])
  File "C:\Users\andri\Anaconda3\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\Users\andri\Anaconda3\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
PermissionError: [WinError 5] Permission Denied

Does anyone understad why this happens and how I could deal with it? Thanks in advance for any help


Solution

  • If "Add to PATH" was enabled during installation, use:

    import subprocess
    subprocess.Popen(['Code.exe'])
    

    Or you can use the full path:

    import subprocess
    subprocess.Popen(['C:\Users\UserName\AppData\Local\Programs\Microsoft VS Code\Code.exe'])
    

    Replace UserName with your user name.