繁体   English   中英

如何通过使用bash脚本传递参数来运行python文件?

[英]How to run python file by passing argument using bash script?

我对 bash 脚本很陌生。 我有一个 .txt 文件,字符串名称由行分隔(每个字符串之间有空格)。

我的.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 文件时,它甚至不起作用。

新:我的.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或类似的实用程序可以帮助您转换此类数据文件。

答案由Inian给出。 不能接受该评论作为答案,所以张贴在这里。

它应该是python3 pythonfile.py -f "$LINE"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM