Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Python script in venv?

Tags:

python

ubuntu

Im trying to start telegram bot in Linux using venv. But bot starts only if venv activated manualy.

Python code:

#!env/bin/python3
# -*- coding: utf-8 -*-
import config
import telebot

bot = telebot.TeleBot(config.token)

@bot.message_handler(content_types=["text"])
def repeat_all_messages(message): 
    bot.send_message(message.chat.id, message.text)

if __name__ == '__main__':
    bot.infinity_polling()

Bot starts with comands:

root@ubuntu-s-1vcpu-1gb-ams3-01:~/jira_bot# source env/bin/activate
(env) root@ubuntu-s-1vcpu-1gb-ams3-01:~/jira_bot# python3 sreda_bot.py

But if i try to start it without activating venv:

root@ubuntu-s-1vcpu-1gb-ams3-01:~/jira_bot# python3 sreda_bot.py
Traceback (most recent call last):
  File "sreda_bot.py", line 4, in <module>
    import telebot
ModuleNotFoundError: No module named 'telebot'
like image 327
Vadim Avatar asked Feb 17 '26 21:02

Vadim


2 Answers

Finally I inserted full path to the interpreter in the venv in shebang line:

#!/root/jira_bot/env/bin/python3

Used ./sreda_bot.py instead of python3 sreda_bot.py. And it works fine.

like image 51
Vadim Avatar answered Feb 20 '26 10:02

Vadim


Considering Python Shebang Syntax is like the following

#!interpreter [optional-arg]

You just need to locate your Virtual ENV's interpreter location.

#!<venv path>/bin/python[3.x]

Thus assuming your Virtual ENV is located at ~/jira_bot base from the following.

root@ubuntu-s-1vcpu-1gb-ams3-01:~/jira_bot# source env/bin/activate
(env) root@ubuntu-s-1vcpu-1gb-ams3-01:~/jira_bot# python3 sreda_bot.py

So your shebang should be #!/root/jira_bot/bin/python3

like image 21
Jonel Dominic Brave Avatar answered Feb 20 '26 09:02

Jonel Dominic Brave