我有一个名为renaming.py的Python脚本,我想使用它来生成许多Bash脚本(超过500个)。Python脚本如下所示:
#!/usr/bin/python
#Script to make multiple Bash scripts based on a .txt file with names of files
#The .txt file contains names of files, one name per line
#The .txt file must be passed as an argument.
import os
import sys
script_tpl="""#!/bin/bash
#BSUB -J "renaming_{line}"
#BSUB -e /scratch/username/renaming_SNPs/renaming_{line}.err
#BSUB -o /scratch/username/renaming_SNPs/renaming_{line}.out
#BSUB -n 8
#BSUB -R "span[ptile=4]"
#BSUB -q normal
#BSUB -P DBCDOBZAK
#BSUB -W 168:00
cd /scratch/username/renaming_SNPs
awk '{sub(/.*/,$1 "_" $3,$2)} 1' {file}.gen > {file}.renamed.gen
"""
with open(sys.argv[1],'r') as f:
for line in f:
line = line.strip()
if not line:
continue
line = line.strip(".gen")
script = script_tpl.format(line=line)
with open('renaming_{}.sh'.format(line), 'w') as output:
output.write(script)作为参数传递给这个Python脚本的.txt文件如下所示:
chr10.10.merged.no_unwanted.formatted.gen
chr10.11.merged.no_unwanted.formatted.gen
chr10.12.merged.no_unwanted.formatted.gen
chr10.13.merged.no_unwanted.formatted.gen
chr10.14.merged.no_unwanted.formatted.gen
chr10.15.merged.no_unwanted.formatted.gen
etc运行Python脚本时,会收到以下错误消息:
Traceback (most recent call last):
File "renaming.py", line 33, in <module>
script = script_tpl.format(line=line)
KeyError: 'sub(/'我不完全确定发生了什么,但我认为
任何帮助都将不胜感激。
发布于 2017-11-30 16:07:40
使用.format时,字符串中的所有{ }都将调用字符串格式。因为您在awk命令中使用了这些字符,所以必须将它们转义。要做到这一点,您需要加倍{{和}}。
script_tpl="""#!/bin/bash
#BSUB -J "renaming_{line}"
#BSUB -e /scratch/username/renaming_SNPs/renaming_{line}.err
#BSUB -o /scratch/username/renaming_SNPs/renaming_{line}.out
#BSUB -n 8
#BSUB -R "span[ptile=4]"
#BSUB -q normal
#BSUB -P DBCDOBZAK
#BSUB -W 168:00
cd /scratch/username/renaming_SNPs
awk '{{sub(/.*/,$1 "_" $3,$2)}} 1' {line}.gen > {line}.renamed.gen
"""这是相关文档。
发布于 2017-11-30 16:07:06
当您调用str.format时,它将尝试格式化{}中的所有内容。
所以这条线就是问题所在:
awk '{sub(/.*/,$1 "_" $3,$2)} 1' {file}.gen > {file}.renamed.gen因为字符串格式化程序试图在格式调用中找到kwargs sub(/和file,这是不存在的,因为您指定的唯一键是line=line。
如果您不希望将它们考虑为格式设置,则需要转义大括号。(格式调用应该删除最后字符串中的一个对。)
awk '{{sub(/.*/,$1 "_" $3,$2)}} 1' {{file}}.gen > {{file}}.renamed.genhttps://stackoverflow.com/questions/47577556
复制相似问题