简体   繁体   中英

Create a Windows 10 desktop shortcut to run a python script in a venv virtual environment

I am trying to create a clickable desktop shortcut for a Windows 10 system that simply executes the following commands that I currently need to repeatedly type in a Windows Powershell:

PS C:\Users\user> cd C:\Users\username\Documents\PyProject
PS C:\Users\username\Documents\PyProject> .venv\scripts\activate
(.venv) C:\Users\username\Documents\PyProject> py -3 .\myscript.py

I've tried a few of the recommended solutions here , here , and here (including a few others not linked) but all fail by immediately closing the console/command window that is supposed to remain open and print out lines of text from the program.

Some of my attempts have included:

  • creating a .bat file that I saved in ...\\PyProject\\ with a shortcut on the desktop.
@echo off
cmd /k "cd /d C:\Users\username\Documents\PyProject\.venv\Scripts & .\activate & cd /d    C:\Users\username\Documents\PyProject & py -3 myscript.py"
  • using pyinstaller and py2exe

Any help would be appreciated. Thanks!

Thanks to @Mofi for the link to comprehensive explanation of different approaches. The easiest solution that worked for me was the following:

(1) Create the following myscript.bat file and save it in the same directory as PyProject :

@echo off
cmd /k "cd /d C:\Users\username\Documents\PyProject\.venv\Scripts & .\activate & cd /d C:\Users\username\Documents\PyProject & py -3 .\myscript.py"

(2) Right-click on that myscript.bat file in the PyProject directory and "Create Shortcut". Drag that shortcut icon to the Desktop, and right-click to view "Properties." They should read:

Target: C:\\Users\\username\\Documents\\PyProject\\myscript.bat

Start In: C:\\Users\\username\\Documents\\PyProject

Shortcut Key: None

Start In: Normal Window

The cmd window that is created after double-clicking on the icon remains open for the duration of the program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM