如何在Python中切换目录执行脚本,解决树莓派pi_video_looper重启问题
Hey there! Let's break down your problems and fix them one by one.
1. How to Switch to a Specific Directory and Execute a Script in Python
You’ve got a few solid options here—some simpler, some more robust:
Option 1: Use os.chdir() to Switch Globally
This changes the working directory of your entire Python process before running the command:
import os try: # Switch to the target directory os.chdir("/home/pi/pi_video_looper") # Execute the script with sudo os.system("sudo ./install.sh") except FileNotFoundError: print("Error: Target directory doesn't exist!") except Exception as e: print(f"An error occurred: {e}")
⚠️ Note: If your script runs other commands later, they’ll use this new directory unless you switch back manually.
Option 2: Use subprocess with cwd (Recommended)
The subprocess module is more flexible than os.system—it lets you capture output, handle errors better, and specify the working directory without changing the global process state:
import subprocess try: # Run the script in the target directory, with sudo result = subprocess.run( ["sudo", "./install.sh"], cwd="/home/pi/pi_video_looper", check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) print("Script output:", result.stdout) except subprocess.CalledProcessError as e: print(f"Script failed with error: {e.stderr}") except FileNotFoundError: print("Error: Script or directory not found!")
The cwd parameter tells subprocess to run the command from that directory directly—no need to alter your Python script’s working directory.
Option 3: Shell Command with &&
If you prefer keeping it all in one shell command, you can chain the directory change and script execution:
import os os.system("cd /home/pi/pi_video_looper && sudo ./install.sh")
This works because the cd and ./install.sh run in the same shell session—Python itself doesn’t switch directories, just the temporary shell instance that runs the command.
2. Automate NAS Mounting & Video Looper Restart on Raspberry Pi
Manually stopping the looper, remounting, and restarting every reboot is a huge hassle. Let’s fix the root cause and automate this workflow:
Step 1: Fix Automatic NAS Mounting
First, make sure your NAS mounts reliably on boot by updating /etc/fstab. Add a line like this (adjust values to match your NAS setup):
//your_nas_ip/your_share /mnt/nas cifs username=your_nas_user,password=your_nas_pass,vers=3.0,x-systemd.automount,x-systemd.mount-timeout=10 0 0
x-systemd.automount: Makes systemd mount the share only when it’s accessed (avoids boot delays if the NAS is offline)x-systemd.mount-timeout=10: Times out after 10 seconds if the NAS isn’t reachable, so your Pi boot doesn’t get stuck
Test it with sudo mount -a—if it works, reboot to confirm it mounts automatically.
Step 2: Make Supervisor Depend on the NAS Mount
Update your video_looper supervisor config (usually at /etc/supervisor/conf.d/video_looper.conf) to ensure it starts only after the NAS is mounted. Add these lines:
[program:video_looper] command=/home/pi/pi_video_looper/start_looper.sh directory=/home/pi/pi_video_looper user=pi autorestart=true startsecs=5 environment=MOUNT_POINT="/mnt/nas"
Then create a wrapper script start_looper.sh to check if the NAS is mounted before starting the looper:
#!/bin/bash MOUNT_POINT="/mnt/nas" # Wait until the NAS is mounted while ! mountpoint -q "$MOUNT_POINT"; do echo "Waiting for NAS mount..." sleep 2 done # Start the video looper ./your_video_looper_executable
Make the script executable with chmod +x start_looper.sh.
Step 3: Allow Passwordless Sudo for Critical Commands
To let your Python script run sudo commands without prompting for a password, edit the sudoers file:
sudo visudo
Add this line at the end:
pi ALL=(ALL) NOPASSWD: /usr/bin/mount, /usr/bin/supervisorctl, /home/pi/pi_video_looper/install.sh
This lets the pi user run those specific commands with sudo without entering a password—perfect for automation.
内容的提问来源于stack exchange,提问作者Elias Schuhmacher

