如何使用在Docker容器中运行的Python API程序创建正确的文件路径



我的python程序正在创建错误的文件路径。形成的文件路径错误:"/autocameratest2\data\TestImages/7_vw_test.png"正确的文件路径应该是:"/autocameratest2/data/TestImages/7_vw_test.png">

The file path is fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '/autocameratest2\data\TestImages/7_vw_test.png'
172.17.0.1 - - [05/Feb/2022 17:34:22] "POST /places?camid=1&image1test=7_vw_test.png&image2perfect=5_vw_master.png HTTP/1.1" 500 -

在python api程序中,以下URLhttp://127.0.0.1:5000/places?camid=1&image1test=7_vw_test.png&image2perfect=5_vw_master.png返回一个json文件。该代码在VisualStudio代码或docker外部运行良好。它的python代码在docker中给出了一个路径问题。

image1test_path = os.path.join(IMAGE_FOLD_PATH,'autocameratest2dataTestImages',image1test)
image2perfect_path = os.path.join(IMAGE_FOLD_PATH,'autocameratest2dataTestImages',image2perfect)
test_results = generate_report(camid, image1test_path, image2perfect_path)
test_names = ['CamId','Blur','check_scale','noise','scrolled','allign','mirror','blackspots','ssim_score','staticlines','rotation_deg']

使用pathlib,python的路径解析库,它有linux、windows类型的路径。您可以在它们之间自由操作。

你的问题是docker在linux上运行,除非另有说明,否则linux使用/for-path和windows\,这就是问题所在。

pathlib.Path将帮助您。

>>> import pathlib
>>> pathlib.Path("xxx/yyyiii.z")
WindowsPath('xxx/yyy/iii.z')

以下方法帮助我创建了所需的文件路径。像这样"/autocameratest2/数据/TestImages";

image1test_path = os.path.join('data','TestImages',image1test)
image2perfect_path = os.path.join('data','TestImages',image2perfect)

下面是我为建造这条小路而尝试的其他技术。这些都很好,尽管它没有解决我的问题。

import pathlib
#image1test_path = pathlib.Path.cwd().joinpath('data', 'TestImages', args.image1test)
#image2perfect_path = pathlib.Path.cwd().joinpath('data', 'TestImages', args.image2perfect)
#image1test_path = pathlib.Path('data', 'TestImages', args.image1test)
#image2perfect_path = pathlib.Path('data', 'TestImages', args.image2perfect)

最新更新