artist / shell_launch_shutdown_script.txt
mswhite's picture
Upload shell_launch_shutdown_script.txt
1be04f5 verified
To create a script that runs a Python program at launch, waits for it to finish, and then initiates a shutdown sequence on a Raspberry Pi, you can follow these steps:
1. **Create the Python Program**: Ensure you have the Python program you want to run. For this example, let's assume it's named `my_program.py`.
2. **Create a Shell Script**: This script will execute your Python program and then shut down the Raspberry Pi.
3. **Set Up the Script to Run at Boot**: Use `cron` or `systemd` to run the script at startup.
Here's how you can implement these steps:
### Step 1: Create the Python Program
Make sure your Python program is ready. For example, `my_program.py`:
```python
# my_program.py
import time
def main():
print("Program started")
time.sleep(10) # Simulate a task that takes 10 seconds
print("Program finished")
if __name__ == "__main__":
main()
```
### Step 2: Create a Shell Script
Create a shell script that will run your Python program and then shut down the Raspberry Pi.
Create a file named `run_and_shutdown.sh`:
```bash
#!/bin/bash
# Run the Python program
python3 /path/to/your/my_program.py
# Wait for the program to finish
wait
# Initiate shutdown
sudo shutdown -h now
```
Make sure to replace `/path/to/your/my_program.py` with the actual path to your Python script.
### Step 3: Make the Shell Script Executable
Run the following command to make the script executable:
```bash
chmod +x /path/to/your/run_and_shutdown.sh
```
### Step 4: Set Up the Script to Run at Boot
You can use `cron` to run the script at startup:
1. Open the crontab file for editing:
```bash
crontab -e
```
2. Add the following line to the crontab file to run the script at boot:
```bash
@reboot /path/to/your/run_and_shutdown.sh
```
3. Save and exit the editor.
Alternatively, you can use `systemd` to create a service that runs the script at startup:
1. Create a new service file:
```bash
sudo nano /etc/systemd/system/run_and_shutdown.service
```
2. Add the following content to the file:
```ini
[Unit]
Description=Run Python Program and Shutdown
[Service]
ExecStart=/path/to/your/run_and_shutdown.sh
Type=oneshot
RemainAfterExit=true
[Install]
WantedBy=multi-user.target
```
3. Save and exit the editor.
4. Enable the service to run at startup:
```bash
sudo systemctl enable run_and_shutdown.service
```
5. Start the service (optional, for testing):
```bash
sudo systemctl start run_and_shutdown.service
```
This setup will ensure that your Python program runs at boot, and once it completes, the Raspberry Pi will shut down. Make sure to test the script and service to ensure everything works as expected.