我有一个文件,叫做LIST.TXT,这是文件的名称的列表:的Python:脚本进行多次的bash脚本
input1.txt
input2.txt
input3.txt
我想建立一个python脚本,这将使一个文件每个这些文件名。更确切地说,我需要它来打印一些文本,合并文件的名称并将其保存到一个唯一的.sh文件中。我的脚本如下:
import os
os.chdir("/Users/user/Desktop/Folder")
with open('list2.txt','r') as f:
lines = f.read().split(' ')
for l in lines:
print "#!/bin/bash\n#BSUB -J",l+".sh","\n#BSUB -o /scratch/DBC/user/"+l+".sh.out\n#BSUB -e /scratch/DBC/user/"+l+".sh.err\n#BSUB -n 1\n#BSUB -q normal\n#BSUB -P DBCDOBZAK\n#BSUB -W 168:00\n"
print "cd /scratch/DBC/user\n"
print 'grep "input"',l+" > result."+l+".txt"
with open('script{}.sh'.format(l), 'w') as output:
output.write(l)
我有几个问题:
- 输出文件只包含文件的名称 - 不是我所打印的内容。
需要明确的是我的输出文件(我应该有3个)应该是这样的:
#!/bin/bash
#BSUB -J input3.sh
#BSUB -o /scratch/DBC/user/input1.sh.out
#BSUB -e /scratch/DBC/user/input3.sh.err
#BSUB -n 1
#BSUB -q normal
#BSUB -P DBCDOBZAK
#BSUB -W 168:00
cd /scratch/DBC/user
grep "input" input3 > result.input3.txt
我很新的Python所以我假设有可能是印刷简单得多的方式和插入我的文字。任何帮助将非常感激。
UPDATE 我现在已经做了下面的脚本,它几乎可以工作。
import os
os.chdir("/Users/user/Desktop/Folder")
with open('list.txt','r') as f:
lines = f.read().split('\n')
for l in lines:
header = "#!/bin/bash \n#BSUB -J %s.sh \n#BSUB -o /scratch/DBC/user/%s.sh.out \n#BSUB -e /scratch/DBC/user/%s.sh.err \n#BSUB -n 1 \n#BSUB -q normal \n#BSUB -P DBCDOBZAK \n#BSUB -W 168:00\n"%(l,l,l)
script = "cd /scratch/DBC/user\n"
script2 = 'grep "input" %s > result.%s.txt\n'%(l,l)
all= "\n".join([header,script,script2])
with open('script_{}.sh'.format(l), 'w') as output:
output.write(all)
这个问题我还有的是,这4个创建脚本,而不是3如我所料:script_input1.sh,script_input2.sh,script_input3.sh和script_sh。最后一个,script_sh只是打印了文本,但没有任何“输入”文本所在的位置。我认为这是因为我的list.txt文件在其末尾有一个“\ n”?但是,我看起来真的没有。有没有解决的办法?也许我可以使用某种长度函数?
没有必要运行真的使用Python,会不会有一个Bash脚本呢? –
不,我真的很想在这种情况下使用Python。我知道Bash可以做到这一点。 – m93
正确的解决方案可能是将变量作为参数传递给静态脚本,而不是写入大量带有变量的静态脚本。 – tripleee