多くのBashスクリプト(500以上)を生成するために使用するrenaming.pyというPythonスクリプトがあります。 Pythonスクリプトはそうのようになります。Bashスクリプトを生成するために使用されるPythonスクリプトのKeyError
#!/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(/'
私はここで何が起こっているのか全くわからない、しかし、私が何を考えている
33行目に何か問題があります。何が問題なのかよく分かりません。私は前にこのような非常に似たスクリプトを使用しています。この行33では、script_tpl内のすべての{line}インスタンスを.txtファイルのエントリに置き換えています(これは.txtファイルの各行に対して1回500回発生します)。
私はKeyErrorで非常に混乱しています。私はLinuxのHPCサーバー(Macラップトップを使用)で作業しています。私はターミナルに直接入力するときにこのawkコマンドを問題なく使用することができました(Bashコマンドとして)。しかし、スクリプトで変数として "印刷"しようとすると、Pythonが混乱しているようです。
ご協力いただければ幸いです。
これはほとんど動作しますが、KeyErrorはなくなりますが、{{file}} .gen> {{file}}。renamed.genに適切なエントリを置き換えません。しかし、ダブル{{}}を取り除くとエラーが再び出る – m93
@ m93 {file}を置き換える場合は、おそらく{line}を意味しますか? {file}変数はありません。私の答えを編集しました。 – nosklo
私の悪い、愚かな間違いoups!ありがとう! – m93