python - 如何通过使用 bash 脚本传递参数来运行 python 文件?
问题描述
我对 bash 脚本很陌生。我有一个 .txt 文件,其中的字符串名称由行分隔(每个字符串之间有空格)。
my.txt 是:
my name
my class
my room
当我使用终端运行我的 python 脚本时。我需要一一传递参数。
python3 python_file.py -f 'my name'
python3 python_file.py -f 'my class'
python3 python_file.py -f 'my room'
它工作正常。我想为每个字符串(我的名字、我的班级和我的房间)单独使用 bash 脚本,并作为 python 脚本的参数传递。
#!/bin/bash
while read LINE; do
#echo ${LINE}
python3 pythonfile.py -f $LINE
done < my.txt
它不起作用,因为每个字符串之间都有一个空格(我的名字),python假定为字符串并显示错误消息
error: unrecognized arguments: name
当我试图在 bash 脚本中加上引号时,它不起作用。
#!/bin/bash
while read LINE; do
echo \'${LINE}\'
#python3 pythonfile.py -f $LINE
done < my.txt
output:
'my name
'my class
'my room
具有相同的错误消息。
当我试图在 .txt 文件中加上引号时,它甚至不起作用。
新:my.txt
'my name'
'my class'
'my room'
同样的错误信息:
error: unrecognized arguments: name
我不想通过从 my.txt 文件中一一读取名称来使用一个 python 脚本来做到这一点。我在 python 脚本中有一些不适合这个的内部编码。因此我想使用bash。
请指导。
解决方案
当我运行这个 shell 脚本时,我的 Mac 似乎给出了预期的输出:
#!/bin/bash
while read LINE; do
echo python3 pythonfile.py -f \'${LINE}\'
#python3 pythonfile.py -f $LINE
done < my.txt
请注意,您在输出中看不到最终报价,也没有从输入中删除任何内容,我怀疑您的数据文件是在 Windows 环境中生成的,并且<CR><LF>
每行都包含终止符。
因此,您的脚本为每行输入输出的内容(shell 去除了终止的换行符)是
'some name<CR>'<LF>
回车的效果是用第二个引号覆盖第一个引号,使其“消失”。通常有一个dos2unix
或类似的实用程序可以帮助您转换此类数据文件。
推荐阅读
- macos - 无法在 osx 上 npm i x509
- javascript - 如何分别显示一个状态的每个项目的点击次数?
- python - 打印我的提要的前 10 行
- amp-html - 如何将一个 amp-story-page 链接到另一个?
- android - 在 Widget 上的 ListView 中显示 SharedPreference 项
- laravel - 隐藏数组 laravel 的索引
- java - Spring boot webjars 未生成,返回 Http 406
- git - 没有相同模式时如何在subgit中排除多个分支
- css - 导航项目因未知原因闪烁
- python - 如何在我自己的 Facebook 页面 (graph-api) 上发布而不在 Facebook 开发人员上创建应用程序