MattV
MattV

Reputation: 1383

Activating a Python virtual environment & changing directory in one shortcut (with cmd)

I'm trying to do the following:

  • Open a CMD prompt
  • Activate a virtual environment
  • Change the current directory to my project folder
  • In essence, I need to execute the following commands sequentially:

    C:\Envs\djangorocks\Scripts\activate
    cd "D:\GitHub\steelrumors"
    

    I've found this link, but creating a shortcut as follows gives me nothing (just a plain CMD prompt in the currently active directory):

    cmd \k "C:\Envs\djangorocks\Scripts\activate" & "cd "D:\GitHub\steelrumors""
    

    After quite a while of searching I'm still doing it manually, any help is appreciated.

    Upvotes: 1

    Views: 4010

    Answers (3)

    dreme
    dreme

    Reputation: 4961

    As an extension to the great answer from @DavidPostill I've added an additional step to run a command from the newly created python env.

    In my example below, I'm launching a new instance of the awesome data mining program, orange, from an anaconda env called orange. I've also cd'ed to the directory containing my orange data files. Note that I had to use the quotation marks "" to make it work.

    C:\Windows\System32\cmd.exe /k "F: && cd \Dropbox\IT\Python\Orange && C:\Users\dreme\Anaconda3\Scripts\activate.bat orange && python -m Orange.canvas"

    Upvotes: 0

    DavidPostill
    DavidPostill

    Reputation: 7921

    "creating a shortcut as follows gives me nothing (just a plain CMD prompt in the currently active directory):"

    cmd \k "C:\Envs\djangorocks\Scripts\activate" & "cd "D:\GitHub\steelrumors""
    

    Observations:

    • cmd \k should be cmd /k.

    • & should be && when using a shortcut.

    • You dont need all the " characters.

    Try the following as the shortcut target:

    cmd /k C:\Envs\djangorocks\Scripts\activate && cd D:\GitHub\steelrumors
    

    Upvotes: 5

    nithins
    nithins

    Reputation: 3192

    Consider creating a batch file (e.g. c:\scripts\launchEnv.cmd) that does something like the following:

    @echo off
    C:\Envs\djangorocks\Scripts\activate
    cd /d "D:\GitHub\steelrumors"
    

    Then create a shortcut that invokes cmd /k c:\scripts\launchEnv.cmd .

    Some notes:

    • the @echo off will prevent the commands from showing up in the cmd windows. If you do want to see the commands, then omit that line from your batch file

    • you'll need the /d param when changing directories to make sure you actually change and navigate there, independent of where the script is currently executing from.

    Upvotes: 3

    Related Questions