Python异常导入问题

时间:2018-06-06 21:51:10

标签: python-3.x docker python-requests

我编写了一个脚本,用于查询ElasticSearch的事件,解析结果并更新状态页面。

该脚本将部署在我们堆栈中的docker容器中。我为这个任务选择了一个官方的python docker图像: python:3.6.5-stretch

一切正常,直到我将脚本停靠。现在,我对导入python-requests

有一个非常古怪的行为

如果我执行脚本,我会得到:

Traceback (most recent call last):                                    
  File "/monitops.py", line 4, in <module>
    import requests   
ImportError: No module named requests

我的shebang和相关的进口:

#!/usr/bin/env python3

import elasticsearch                                                                                                                                                                                                   
import requests

现在,如果我放到任何python shell,无论是python,python3还是usr / bin / env python3,我都可以正常导入请求:

root@f37fedb9b7b4:/# python
Python 3.6.5 (default, May  5 2018, 03:05:30)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>>

root@f37fedb9b7b4:/# python3
Python 3.6.5 (default, May  5 2018, 03:05:30)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>>

root@f37fedb9b7b4:/# /usr/bin/env python3
Python 3.6.5 (default, May  5 2018, 03:05:30)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>>

此外,python和python3是相同可执行文件的符号链接,python3.6:

root@f37fedb9b7b4:/# which python
/usr/local/bin/python
root@f37fedb9b7b4:/# ls -l /usr/local/bin/python
lrwxrwxrwx 1 root staff 7 May  5 03:06 /usr/local/bin/python -> python3
root@f37fedb9b7b4:/# which python3
/usr/local/bin/python3
root@f37fedb9b7b4:/# ls -l /usr/local/bin/python3
lrwxrwxrwx 1 root staff 9 May  5 03:06 /usr/local/bin/python3 -> python3.6
root@f37fedb9b7b4:/# ls -l /usr/local/bin/python3.6
-rwxr-xr-x 2 root staff 33024 May  5 03:05 /usr/local/bin/python3.6

/ usr / local / bin / python

调用脚本运行而不抱怨导入的唯一方法
/usr/local/bin/python myscript.py

[ The script runs like expected ]

我真的很想知道为什么会这样,我找到了一个解决方法,但需要了解这种行为

编辑:

我从crontab运行脚本,我在入口点创建了它:

#!/bin/bash  

export ES_ENDPOINT

if [[ -z $ES_ENDPOINT || -z $CRONTAB_OPTS ]]; then
    echo -e "\nThe required variables are not set!\n"
    exit 2
fi

echo -e "${CRONTAB_OPTS} python3 /monitops.py >> /var/log/cron \n" | crontab - 

touch /var/log/cron

service cron restart

tail -f /var/log/cron

我已经尝试使用python,python3运行crontab并执行它,我在/etc/cron.d中尝试了系统cron,问题仍然存在。

在我的Dockerfile中,我使用pip安装请求和elasticsearch:

RUN pip install requests elasticsearch

0 个答案:

没有答案