Running a Python Script in the Background with .exe and Startup
Running a Python Script in the Background with .exe and Startup
If you've ever wanted to run a Python script discreetly in the background and have it start automatically when your PC boots up, you can achieve this by converting your Python script into a standalone executable (.exe) using PyInstaller. Below is a step-by-step guide along with a sample Python script:
Step 1: Install PyInstaller
Ensure you have PyInstaller installed. If not, run the following command in your terminal or command prompt:
pip install pyinstaller
Step 1: Convert Python Script to .exe
Navigate to the directory containing your Python script and run the following command to convert it into a single executable file:
pyinstaller --onefile --noconsole your_script_name.py
pyinstaller --onefile --noconsole your_script_name.py
Replace your_script_name.py with the actual name of your Python script.
Step 3: Sample Python Script
Here's a sample Python script that creates a shortcut in the Windows Startup folder, ensuring your script runs in the background when your PC starts:
import os
import win32com.client
import platform
import time
import logging
import time
import sys
from datetime import datetime
global fullPath,mypath
# when your want's things from exe file
if getattr(sys, 'frozen', False):
fullPath = os.path.abspath(sys.executable)
mypath = os.path.dirname(fullPath)
else:
# if user want this things when code not in exe
fullPath = os.path.abspath(__file__)
mypath = os.path.dirname(fullPath)
logging.basicConfig(
filename= f"{mypath}\/text.log",
level=logging.DEBUG
)
def get_startup_folder():
system_platform = platform.system()
if system_platform == "Windows":
startup_folder = os.path.join(os.getenv("APPDATA"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup")
return startup_folder
else:
raise OSError("Unsupported platform")
def create_shortcut(target_path, shortcut_path, icon_path=None):
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortcut(shortcut_path)
shortcut.TargetPath = target_path
if icon_path:
shortcut.IconLocation = icon_path
shortcut.Save()
def createLogs():
custom_info = "Log:"
print(fullPath)
print(mypath)
while True:
current_datetime = datetime.now()
logging.debug(f'{custom_info} - {current_datetime}')
print(current_datetime)
time.sleep(1)
# first executable
def main():
# Find the startup folder
startup_folder = get_startup_folder()
# Get information about the current script
target_file_path = fullPath
file_name = os.path.splitext(os.path.basename(fullPath))[0]
# Create the shortcut path
shortcut_path = os.path.join(startup_folder, f"{file_name}.lnk")
# my orignal folder locations
# Create the shortcut
create_shortcut(target_file_path, shortcut_path, icon_path=None)
# create log file in seconds
createLogs()
if __name__ == "__main__":
main()
Step 4: Execution
Run the generated .exe file, and your Python script will start running in the background. Additionally, the script ensures it starts automatically when your PC boots up by placing a shortcut in the Windows Startup folder.
This approach provides a discreet and efficient way to run Python scripts as background tasks on Windows systems.
Feel free to customize the script and instructions based on your specific requirements.**
GITHUB:- avinashtare
Comments
Post a Comment