首页 > 解决方案 > 带有argparse参数的相同python命令在shell脚本中不起作用

问题描述

我正在开发 Ubuntu 16.04。如果我直接在终端中运行命令行,python 脚本可以正确识别 argparse 参数,但是如果我在 shell 脚本中编写并运行它,相同的命令将无法正常工作。

不起作用的 argparse 参数是--checkpoint_file,python 代码在其中检查检查点文件是否存在,然后加载经过训练的模型。在运行 shell 脚本时,我打印了checkpoint_file字符串,它看起来正确,但它无法通过os.path.isfile并且模型无法加载。

parser = argparse.ArgumentParser()
parser.add_argument('--checkpoint_dir', default='./checkpoint', type=str)
parser.add_argument('--checkpoint_file', default='', type=str)
opt = parser.parse_args()

checkpoint_file = os.path.join(opt.checkpoint_dir, opt.checkpoint_file)
print(checkpoint_file) 
assert os.path.isfile(checkpoint_file), \
        "Error: no checkpoint %s found!" % checkpoint_file
checkpoint = torch.load(checkpoint_file)

Run_script.sh我在文件夹下的shell 脚本中编写了命令script

CUDA_VISIBLE_DEVICES=1 python Code_101.py --batch_size 4 --checkpoint_file Model_name/40_checkpoint.pth.tar

并且sh script/Run_script.sh,输出为:

./checkpoint/Model_name/40_checkpoint.pth.tar
AssertionError: Error: no checkpoint ./checkpoint/Model_name/4 found!point.pth.tar

但是当我直接在终端中运行相同的命令时,它可以正常工作。怎么了?

编辑

如果 Icp script/Run_script.sh .sh Run_script.sh,会发生同样的错误。

如果我使用--checkpoint_dir /home/my_folder/checkpoint,会发生同样的错误。

当我在没有参数的情况下训练模型时--checkpoint_file,shell 脚本可以正常工作。

标签: pythonpython-3.xshell

解决方案


也许shell脚本是从不同的目录启动的?这将改变.相对路径中的结果。

在使用之前尝试将其转换checkpoint_dir为绝对路径。os.path.abspath()如果错误仍然存​​在,它会告诉它在文件系统中的哪个位置查找您的文件。

最有可能的是,您希望基于os.path.abspath(os.path.dirname(__file__))而不是基于 定义默认路径.


推荐阅读