簡體   English   中英

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

[英]argparse dealing with strings and spaces in bash commands

我有一個想要在 HPC 集群上運行的 bash 作業。 在我的 bash 腳本中,我使用的是 Job Arrays,所以我不會為要提交的每個作業編寫單獨的腳本。 為了提高效率,我將所有要執行的命令(數組中的每個作業 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來解析 arguments。 這是我的 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)

我有以下兩個問題:

  1. 我的程序的output如下(以第一份工作為例)
     My SLURM_ARRAY_TASK_ID: 1 'Sofia' 'Ghnam'
    我不希望''成為印刷 output 的一部分。 我不確定它們為什么會出現; 通常我會在''中傳遞任何字符串,因為字符串可能包含空格。 發生這種情況時,請參閱第二個項目符號:
  2. 在最后的工作中,我傳遞的字符串在--fname 'Leen Khaled'之間有間隔,我遇到了以下錯誤

我的 SLURM_ARRAY_TASK_ID:4 用法:mybashtest.py [-h] [--fname FNAME] [--lname LNAME] mybashtest.py:錯誤:無法識別的 arguments:Khaled' srun:錯誤:onode08:任務 0:以退出代碼 2 退出3.列表項

經過幾天的嘗試解決這個問題,以下是我所做的:

  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

這將是 output:

Leen Khaled Gh

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM