简体   繁体   English

在 shell 脚本中运行 python3 时出现 ModulesNotFound 错误

[英]ModulesNotFound Error when running python3 in shell script

I have my python3 path under /usr/bin , any my pip path under /.local/bin of my local repository.我的 python3 路径在/usr/bin下,我的任何/.local/bin路径在我的本地存储库的 /.local/bin 下。 With some pip modules installed, I can run my code successfully through python3 mycode.py .安装了一些 pip 模块后,我可以通过python3 mycode.py成功运行我的代码。

But I tried to run the shell script:但我尝试运行 shell 脚本:

#!/usr/bin
echo "starting now..."
nohup python3 mycode.py > log.txt 2>&1 &
echo $! > pid
echo "mycode.py started at pid: "
cat pid

and my python code:和我的 python 代码:

mycode.py我的代码.py

#!/usr/bin/env python3
from aiocqhttp import CQHttp, Event, Message, MessageSegment
...
...
...

It gives me:它给了我:

Traceback (most recent call last):
  File "mycode.py", line 2, in <module>
    from aiocqhttp import CQHttp, Event, Message, MessageSegment
ModuleNotFoundError: No module named 'aiocqhttp'

I tried to replace the interpreter of the shell script with my local path, but it doesn't help.我试图用我的本地路径替换 shell 脚本的解释器,但它没有帮助。 How should I run my python codes using the shell script?我应该如何使用 shell 脚本运行我的 python 代码?

In your case, the aiocqhttp was installed in your home directory, and when you invoke the script by sudo , python3 will not be able to know to search in your home (because it is root that is running the process).在您的情况下, aiocqhttp安装在您的主目录中,当您通过sudo调用脚本时, python3将无法知道要在您的主目录中进行搜索(因为运行该进程的是根目录)。 You may solve it using these two approaches:您可以使用以下两种方法解决它:

Method 1:方法一:

sudo -H pip3 install -U aiocqhttp

Install this module system-wide so that every user can find it.在系统范围内安装此模块,以便每个用户都能找到它。

Method 2:方法二:

sudo PYTHONPATH=/home/a495488027/.local/lib/python3.8/site-packages python3 mycode.py

Temporarily add the python module search path to sudo and run the code.暂时将python模块搜索路径加入sudo ,运行代码。 This is when you doesn't want to install the package system-wide.这是您不想在系统范围内安装 package 的时候。


Back to your problem,回到你的问题,

sudo PYTHONPATH=/home/a495488027/.local/lib/python3.8/site-packages bash script.sh

should do the work.应该做的工作。

Quick solution: install the same that you have installed with sudo and then it will be accesible for all users快速解决方案:安装您使用 sudo 安装的相同内容,然后所有用户都可以访问它

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

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