python - 带有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 脚本可以正常工作。
解决方案
也许shell脚本是从不同的目录启动的?这将改变.
相对路径中的结果。
在使用之前尝试将其转换checkpoint_dir
为绝对路径。os.path.abspath()
如果错误仍然存在,它会告诉它在文件系统中的哪个位置查找您的文件。
最有可能的是,您希望基于os.path.abspath(os.path.dirname(__file__))
而不是基于 定义默认路径.
。
推荐阅读
- javascript - 当我向我的 svg 添加标题和副标题时,它们会出现在我的图形上方
- generics - 在 DAML 中是否可以有一个通用参数来选择,而模板本身不是通用的?
- openapi - 如何使用 OpenAPI-3.0 表达 JSON-API 稀疏字段集
- sml - 如何在 ML 中创建平面列表函数?
- c - 使用 Visual Studio Code 任务自动化多个文件夹中的 C makefile
- html - 使用 office-ui-fabric 的 ms-hidden 类的问题
- sql - 在 MS Azure SQL 数据库中执行 case 语句时出现数据类型不匹配错误
- reactjs - 设置 React Material UI Checkbox 数据属性
- python - Python 在命令行上启动程序后我无法转向我的代码
- google-cloud-firestore - Algolia Livesearch 将 Firestore 数据索引到 Algolia