[英]Docker Python script can't find file
我已經成功構建了一個Docker容器並將我的應用程序文件復制到Dockerfile中的容器中。 但是,我正在嘗試執行一個引用輸入文件的Python腳本(在Docker構建期間復制到容器中)。 我似乎無法弄清楚為什么我的腳本告訴我它無法找到輸入文件。 我包括我用於構建下面容器的Dockerfile,以及正在查找它找不到的輸入文件的Python腳本的相關部分。
Dockerfile:
FROM alpine:latest
RUN mkdir myapplication
COPY . /myapplication
RUN apk add --update \
python \
py2-pip && \
adduser -D aws
WORKDIR /home/aws
RUN mkdir aws && \
pip install --upgrade pip && \
pip install awscli && \
pip install -q --upgrade pip && \
pip install -q --upgrade setuptools && \
pip install -q -r /myapplication/requirements.txt
CMD ["python", "/myapplication/script.py", "/myapplication/inputfile.txt"]
Python腳本的相關部分:
if len(sys.argv) >= 2:
sys.exit('ERROR: Received 2 or more arguments. Expected 1: Input file name')
elif len(sys.argv) == 2:
try:
with open(sys.argv[1]) as f:
topics = f.readlines()
except Exception:
sys.exit('ERROR: Expected input file %s not found' % sys.argv[1])
else:
try:
with open('inputfile.txt') as f:
topics = f.readlines()
except:
sys.exit('ERROR: Default inputfile.txt not found. No alternate input file was provided')
主機上的Docker命令導致錯誤:
sudo docker run -it -v $HOME/.aws:/home/aws/.aws discursive python \
/discursive/index_twitter_stream.py
上面命令的錯誤:
錯誤:找不到默認的inputfile.txt。 沒有提供備用輸入文件
AWS的內容來自關於如何將主機的AWS憑證傳遞到Docker容器以用於與AWS服務交互的教程。 我使用了這里的元素: https : //github.com/jdrago999/aws-cli-on-CoreOS
到目前為止,我已經確定了兩個問題。 Maya G在下面的評論中指出了第三名。
條件邏輯不正確
你需要替換:
if len(sys.argv) >= 2:
sys.exit('ERROR: Received 2 or more arguments. Expected 1: Input file name')
附:
if len(sys.argv) > 2:
sys.exit('ERROR: Received more than two arguments. Expected 1: Input file name')
請記住,給腳本的第一個參數始終是它自己的名字。 這意味着您應該期望sys.argv
有1個或2個參數。
查找默認文件的問題
另一個問題是您的docker容器的工作目錄是/home/aws
,因此當您執行Python腳本時,它將嘗試解析相對於此的路徑。
這意味着:
with open('inputfile.txt') as f:
將解析為/home/aws/inputfile.txt
,而不是/home/aws/myapplication/inputfile.txt
。
您可以通過將代碼更改為:
with open('myapplication/inputfile.txt') as f:
或者(首選):
with open(os.path.join(os.path.dirname(__file__), 'inputfile.txt')) as f:
(上述變化的來源 )
使用CMD
與ENTRYPOINT
看起來你的腳本似乎沒有接收myapplication/inputfile.txt
作為參數。 這可能是CMD
的怪癖。
我不是這兩個操作之間的區別清楚100%,但我總是用ENTRYPOINT
在我的Dockerfiles,它給了我不悲傷。 看到這個答案並嘗試替換:
CMD ["python", "/myapplication/script.py", "/myapplication/inputfile.txt"]
附:
ENTRYPOINT ["python", "/myapplication/script.py", "/myapplication/inputfile.txt"]
(感謝Maya G)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.