我有一个要导入模块opc的python文件download.py
现在,从shell脚本build.sh调用此python文件,如下所示:
python3 $(pwd)/scripts/download.py -d $dir_name当我运行shell脚本时,我得到以下错误:
Traceback (most recent call last):
File "/home/ray/Desktop/repo/image-builder/scripts/download.py", line 14, in <module>
from opc.utils import file_utils, logger
ModuleNotFoundError: No module named 'opc'下面是shell脚本的调用方式:
sudo sh scripts/src/build.sh我有一个虚拟环境,在那里我已经安装了这个软件包。这个包也在那里
>pip list
Package Version
--------------------------------- -------
attrs 21.2.0
.
.
opc 0.8.0有趣的是,当我直接运行python代码时,如下所示
python3 scripts/download.py -d dir_path它工作得很好。我不会不得到ModuleNotFoundError错误。
此外,这也可以很好地工作:
❯ python3
Python 3.8.10 (default, Sep 28 2021, 16:10:42)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import opc.utils.global_vars as g
>>> print(g.LOCAL_HOST)
127.0.0.1
>>>目录结构:
/home/ray/Desktop/repo/image-builder/scripts/download.py
/home/ray/Desktop/repo/image-builder/scripts/src/build.sh我从以下位置运行命令:
/home/ray/Desktop/repo/image-builder发布于 2021-11-18 18:07:49
这可能是因为当您调用shell脚本时,python路径与运行Python解释器时不同。如果是这样的话,有几种方法可以解决这个问题。
如果手动切换到与download.py相同的目录并从那里运行python脚本,会发生什么?类似于:
cd scripts
python download.py -d <some-dir>这行得通吗,或者你还会遇到同样的问题吗?
在像这样的shell脚本中,我首先要确保脚本总是从文件系统中完全相同的位置调用python应用程序,这样我就不会遇到这些python路径问题。如果您确信python download.py -d <some-dir>与download.py位于同一目录中,那么您可以向您的shell脚本添加类似以下内容的内容(假设您的shell脚本和download.py位于同一目录中):
pushd "${0%/*}" # this changes directory to the directory where the shell script itself lives
# do your stuff here - run your python app, etc.
popd # returns to whatever directory we were originally in通过这种方式,我可以随时从我所在的任何目录调用shell脚本,并且我知道它将以相同的方式运行-当前目录不再相关。
我不会使用$(pwd),因为它会给出当前目录,如果您这样做,那么您的shell脚本只有在从正确的目录中调用时才能正常工作。
https://stackoverflow.com/questions/70024414
复制相似问题