How to run a python script using pm2 in EC2 instance in aws
Suppose 👍 you have this structure:
habit-tracker/
├── bot.py
└── myvenv/
and you want to run bot.py
using PM2, but with the Python interpreter from myvenv
.
Here’s the step-by-step guide:
1. Install PM2 (if not installed)
npm install -g pm2
2. Use your virtual environment’s Python
Find the full path of your virtualenv’s Python:
cd habit-tracker
pwd # (note this absolute path)
# Now check your venv Python path:
./myvenv/bin/python --version
Suppose it’s /home/user/habit-tracker/myvenv/bin/python
.
3. Start your bot.py with PM2
Run this:
pm2 start /home/user/habit-tracker/myvenv/bin/python -- bot.py
Explanation:
pm2 start <python_interpreter> -- <script>
- This tells PM2 to use the venv’s Python to run your script.
4. (Optional) Give it a name
pm2 start /home/user/habit-tracker/myvenv/bin/python --name habit-bot -- bot.py
5. Save process list so it restarts on reboot
pm2 save
pm2 startup
Follow the instructions after pm2 startup
.
6. Check logs
pm2 logs habit-bot
✅ That’s it. Now your bot.py
will run under myvenv
and be managed by PM2.
Do you also want me to show you how to set this up with a ecosystem.config.js
file so you don’t have to type the full command each time?