argparse 处理 bash 命令中的字符串和空格

argparse dealing with strings and spaces in bash commands

我有一个 bash 作业,我想 运行 在 HPC 集群上。在我的 bash 脚本中,我使用的是作业数组,因此我不会为每个要提交的作业编写单独的脚本。为了提高效率,我将我要执行的所有命令(数组中每个作业的 1 个命令)存储在 .txt 文件中,如下所示:

python mybashtest.py --fname 'Sofia' --lname 'Ghnam'
python mybashtest.py --fname 'Loulou' --lname 'Ghnam'
python mybashtest.py --fname 'Leen' --lname 'hkg02'
python mybashtest.py --fname 'Leen Khaled' --lname 'Gh'

我正在使用 python 的 argparse 来解析参数。这是我的 python 脚本:

import argparse

parser = argparse.ArgumentParser(description='My script')
parser.add_argument('--fname', type=str, default='')
parser.add_argument('--lname', type=str, default='')

parsed_args = parser.parse_args()

if __name__ == '__main__':
    print(parsed_args.fname + " " + parsed_args.lname)

这是我为了 运行 作业数组而使用的 shell 脚本:

#!/usr/bin/env bash

#SBATCH --job-name=all_jobs
#SBATCH --account=hkg02
#SBATCH --nodes=1
#SBATCH --array=1-3

module load python/3
# Print the task id.
echo "My SLURM_ARRAY_TASK_ID: " $SLURM_ARRAY_TASK_ID
# here the head -n $SLURM_ARRAY_TASK_ID reads the first n lines 
# from the txt file of job command, the # tail -n 1 takes the last line of those.
# A simple trick to associate the Job array number 
# with the appropriate line number in the txt file of command
srun $(head -n $SLURM_ARRAY_TASK_ID jobstest.txt | tail -n 1)

我有以下 2 个问题:

  1. 我的程序输出如下(以第一份工作为例)
    My SLURM_ARRAY_TASK_ID:  1
    'Sofia' 'Ghnam'
    
    我不希望 '' 成为打印输出的一部分。我不确定他们为什么会出现; 通常我在 '' 中传递任何字符串,因为字符串可能有空格。什么时候 发生这种情况,请参阅第二个项目符号:
  2. 在最后的作业中,我传递的字符串在 --fname 'Leen Khaled' 之间有间隔,我有以下错误

My SLURM_ARRAY_TASK_ID: 4 usage: mybashtest.py [-h] [--fname FNAME] [--lname LNAME] mybashtest.py: error: unrecognized arguments: Khaled' srun: error: onode08: task 0: Exited with exit code 2 3. List item

经过几天的努力解决这个问题,以下是我所做的:

  1. 为了解决问题 1,bash 接受字符串 没有空格 原样,因此不需要将它们包含在双引号 "" 或单引号 ''
  2. 为了解决问题 2,事实证明 bash 接受带空格的字符串,我们必须将这些字符串初始化为变量,然后适当地使用它们,如下所示:
#!/usr/bin/env bash

#SBATCH --job-name=all_jobs
#SBATCH --account=hkg02
#SBATCH --nodes=1

var1="Leen Khaled"
module load python/3
python mybashtest.py --fname "${var1}" --lname Gh

这将输出:

Leen Khaled Gh