[英]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)
我有以下兩個問題:
My SLURM_ARRAY_TASK_ID: 1 'Sofia' 'Ghnam'
我不希望''
成為印刷 output 的一部分。 我不確定它們為什么會出現; 通常我會在''
中傳遞任何字符串,因為字符串可能包含空格。 發生這種情況時,請參閱第二個項目符號:--fname 'Leen Khaled'
之間有間隔,我遇到了以下錯誤我的 SLURM_ARRAY_TASK_ID:4 用法:mybashtest.py [-h] [--fname FNAME] [--lname LNAME] mybashtest.py:錯誤:無法識別的 arguments:Khaled' srun:錯誤:onode08:任務 0:以退出代碼 2 退出3.列表項
經過幾天的嘗試解決這個問題,以下是我所做的:
""
或單引號''
#!/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.