简体   繁体   English

如何在 venv 中运行 Python 脚本?

[英]How to run Python script in venv?

Im trying to start telegram bot in Linux using venv.我正在尝试使用 venv 在 Linux 中启动电报机器人。 But bot starts only if venv activated manualy.但只有当 venv 手动激活时,机器人才会启动。

Python code: Python代码:

#!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: Bot 以命令开头:

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:但是,如果我尝试在不激活 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'

Finally I inserted full path to the interpreter in the venv in shebang line:最后,我在 shebang 行的 venv 中插入了解释器的完整路径:

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

Used ./sreda_bot.py instead of python3 sreda_bot.py .使用./sreda_bot.py而不是python3 sreda_bot.py And it works fine.它工作正常。

Considering Python Shebang Syntax is like the following考虑到Python Shebang语法如下

#!interpreter [optional-arg]

You just need to locate your Virtual ENV 's interpreter location.您只需要找到您的Virtual ENV的解释器位置。

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

Thus assuming your Virtual ENV is located at ~/jira_bot base from the following.因此,假设您的虚拟 ENV位于~/jira_bot基地,如下所示。

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所以你的shebang应该是#!/root/jira_bot/bin/python3

The purpose of virtual environments in Python is to create a physical separation between projects and their modules. Python 中的虚拟环境的目的是在项目及其模块之间创建物理分离。 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.在这种情况下,您在虚拟环境中安装的遥控机器人模块不在虚拟环境之外的 scope(可供使用)中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM