Search code examples
pythonmacosvisual-studio-codeterminalsubprocess

Using Terminal, Launch VSCode into a project folder and open a project file


I am writing a Python Script and I want to use subprocess - basically MacOS terminal (Flavor probably not important) to launch VSCode (installed) into a project directory e.g. ~/workspace/my/project/ and have it open a file within that folder e.g. ~/workspace/my/project/javascript-file.js. How can I achieve this?

This is a self answered entry for clarification of others who may be looking for similar solutions when writing Python Scripts as local development tools.


Solution

  • VSCode editor is opened using the code executable in MacOS Terminal, and thus can be used the same way when running python code.

    The code executable enables you to pass several arguments (specifying paths to 'open' once the editor launches)

    try:
        # This will raise if code does not exist on the machine
        subprocess.run(['code', '-r', '/workspace/folder', f'/workspace/folder/file.js'], check=True, text=True)
    except:
        print(f'Failed to launch VSCode')