首页 > 解决方案 > 如何通过使用 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。

请指导。

标签: pythonbash

解决方案


当我运行这个 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或类似的实用程序可以帮助您转换此类数据文件。


推荐阅读