我写了一个bash脚本,
for dcd in ${workdir}/*.dcd; do
dcd_name2="$(basename "$dcd")"
dcd_name="${dcd_name2/.dcd/}"
# print a python script
printf " # 1-load dcd file
dcd = parseDCD('${dcd}')
# 2- do something with the dcd file
dcd.superpose() lala
# 3- Plotting results
import matplotlib.pyplot as plt
plt.figure(figsize=(9,8))
showFractVars(md_ensemble)
plt.savefig( 'results_${dcd_name}.png' ) > ./my_python_script.py
python ./my_python_script.py
done
现在,我需要修改算法,以循环方式在一个脚本中加载所有DCD文件,例如对于10个dcd文件,python脚本应如下所示
dcd1 = parseDCD('${dcd1}')
dcd2 = parseDCD('${dcd2}')
dcd3 = parseDCD('${dcd3}')
# 2- do something with the dcd file
dcd1.superpose() lala
dcd2.superpose() lala
dcd3.superpose() lala
# 3- Plotting results
import matplotlib.pyplot as plt
plt.figure(figsize=(9,8))
showFractVars(dcd1, dcd2,dcd3)
plt.savefig( 'results_${dcd_name}.png' )
如何修改我的第一个bash脚本中的“ for循环”以完成此任务?
答案 0 :(得分:1)
我认为不需要bash脚本。
我的建议是,您应该使用glob
python模块并编写一个python脚本,该脚本可以执行给定工作目录所需的所有逻辑
这是我编写的示例脚本,这是您可能解决此问题的最佳方法:
# Imports
import argparse
import os
from glob import glob
# Third party imports
import matplotlib.pyplot as plt
# Constants
RESULT_NAME_TEPLATE = 'results_{file_name}.png'
def parse_dcd():
# Your logic...
pass
def handle_dcd_file(file_name):
dcd = parse_dcd('${dcd}')
# 2- do something with the dcd file
dcd.superpose()
# 3- Plotting results
plt.figure(figsize=(9,8))
showFractVars(md_ensemble)
plt.savefig(RESULT_NAME_TEPLATE.format(file_name=file_name))
def main(input_directory):
dcd_files = glob(os.path.join(input_directory, '*.dcd'))
for file_name in dcd_files:
print "Handling {file_name}".format(file_name=file_name)
handle_dcd_file(file_name)
print "Finished handling {} dcd files from '{}'".format(len(dcd_files), os.path.abspath(input_directory))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Your program description")
parser.add_argument('input_directory', nargs='?', default='.')
args = parser.parse_args()
if not os.path.isdir(args.input_directory):
parser.error("The input directory at '{}' does not exist!".format(args.input_directory))
main(args.input_directory)
用法示例:
该脚本接受一个可选的input_directory
命令行参数。如果没有提供,则使用当前目录:
当前目录
python dcd_parser.py
给出目录
python dcd_parser.py /home/user/example/dir