Docker Python脚本找不到fi

2024-05-02 17:37:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经成功地构建了一个Docker容器,并将我的应用程序文件复制到Dockerfile中的容器中。但是,我正在尝试执行一个Python脚本,该脚本引用一个输入文件(在Docker构建期间复制到容器中)。我似乎不明白为什么我的脚本告诉我它找不到输入文件。我包括了下面用来构建容器的Dockerfile,以及Python脚本的相关部分,该脚本正在寻找它找不到的输入文件。

文档文件:

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

上面命令的错误:

ERROR: Default inputfile.txt not found. No alternate input file was provided

AWS的内容来自一个关于如何将主机的AWS凭证传递到Docker容器中以用于与AWS服务交互的教程。我用了这里的元素:https://github.com/jdrago999/aws-cli-on-CoreOS


Tags: installpip文件dockerruntxt脚本aws
1条回答
网友
1楼 · 发布于 2024-05-02 17:37:20

到目前为止,我发现了两个问题。玛雅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:

Source用于上述变体)

使用CMDENTRYPOINT

似乎你的脚本显然没有把myapplication/inputfile.txt作为参数接收。这可能是CMD的一个怪癖。

我不完全清楚这两种操作之间的区别,但我总是在我的文档文件中使用ENTRYPOINT,这并没有让我感到悲伤。请参阅this answer并尝试替换:

CMD ["python", "/myapplication/script.py", "/myapplication/inputfile.txt"]

使用:

ENTRYPOINT ["python", "/myapplication/script.py", "/myapplication/inputfile.txt"]

(谢谢玛雅G)

相关问题 更多 >