To run two separate scripts automatically one after the other, ensuring the second script starts only after the first one finishes, you can use simple command chaining techniques depending on your environment. Since you want to train two models sequentially on a single GPU, this approach will help you avoid GPU resource conflicts.
Running Scripts Sequentially in a Shell (Linux/Mac/Windows WSL)
- Use the
&& operator between the commands. This ensures the second script runs only if the first script completes successfully (exit code 0).
Example:
python train_model1.py && python train_model2.py
This runs train_model1.py first, and only after it finishes successfully, train_model2.py starts[2][4].
- Alternatively, you can put the commands on separate lines in a shell script file:
#!/bin/bash
python train_model1.py
python train_model2.py
Running this script will execute the two scripts sequentially, with the second starting after the first finishes regardless of success or failure[2].
Running Scripts Sequentially in Windows Batch
- Use
&& similarly in a batch file or command prompt:
python train_model1.py && python train_model2.py
This waits for the first to finish before starting the second[3].
Using a Master Python Script
You can create a Python script that calls the two training scripts sequentially using subprocess:
import subprocess
subprocess.run(["python", "train_model1.py"], check=True)
subprocess.run(["python", "train_model2.py"], check=True)
This runs the first script and waits for it to complete before running the second. If the first script fails, it raises an error and stops[3].
Notes for Training Two Models on a Single GPU Sequentially
- Running the two training scripts sequentially ensures only one model uses the GPU at a time, avoiding memory conflicts.
- Make sure each script releases GPU memory properly after finishing.
- If you want to automate this regularly, you can schedule the sequential command/script with cron (Linux) or Task Scheduler (Windows).
- For more complex workflows, tools like Luigi or Airflow can orchestrate sequential jobs, but for simple sequential runs, chaining commands or a master script is sufficient[3].
Summary Table
| Method | How to Run Sequentially | Notes |
|---|
| Shell command line | python script1.py && python script2.py | Second runs only if first succeeds |
| Shell script file | python script1.py (newline) python script2.py | Runs sequentially regardless of success |
| Windows batch file | python script1.py && python script2.py | Same as shell command |
| Python master script | Use subprocess.run() calls sequentially | More control, can handle errors |
Using these methods, you can train two models on a single GPU one after the other automatically without manual intervention.