skip to Main Content

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'

3

Answers


  1. Chosen as BEST ANSWER

    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.


  2. The purpose of virtual environments in Python is to create a physical separation between projects and their modules. In this case, the telebot module that you installed in the virtual environment, isn’t in scope (available for use) outside of the virtual environment.

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search