GRAPES MESO模式学习笔记08-3 —— 使用Python改写脚本
之前文章中确认SMS及LoadLeveler都支持Python,下面进行从shell脚本到Python脚本的改写工作。
基本元素
首先分析下模式运行脚本中使用的基本语句和命令:
变量设置
编程语言中最基本的赋值语句
时间计算
模式预报与时间密不可分,需要使用时间增量计算时间,并对格式化输出。
Shell中没有提供这方面的命令,我们使用SMS提供的可执行程序{shell}smsdate{/shell}或者一个用Perl写的脚本{shell}newdate{/shell}来完成实现的计算。
Python的datetime模块完美实现我们需要的时间计算、格式化输出功能。{python}datetime.timedelta{/python}提供增量时间计算功能。
环境变量设置
Shell中使用{shell}export{/shell}命令,Python中使用{python}os.environ{/python}对象
目录文件操作
脚本中最常见的就是IO操作。涉及目录和文件的检测、创建、修改、连接、移动和删除等操作。Shell脚本最强大的功能除了管道就是IO操作了。
Python中也提供大量目录文件IO功能,主要集中在os模块,os.path模块和shutil模块。
目录操作
检测目录
Shell
test -d path_to_dir
Python
os.path.isdir(path_to_dir)
创建目录
Shell
mkdir dir_name mkdir -p path_to_dir
Python
os.mkdir(dir_name) os.makedirs(path_to_dir)
移动目录
Shell
mv old_dir new_dir
Python
os.rename(old_dir, new_dir)
复制目录
Shell
cp old_dir new_dir
Python
shutil.copytree(old_dir, new_dir)
连接目录
软连接,一般业务脚本中都为软连接
Shell
ln -s original_dir link_dir
Python
os.symlink(original_dir, link_dir)
硬链接
Shell
ln original_dir link_dir
Python
os.link(original_dir, link_dir)
删除连接使用{python}os.remove{/python}
删除目录
Shell
rm -rf path_to_dir
Python
shutil.retree(path_to_dir)
文件操作
检测
Shell
test -f path_to_file
Python
os.path.isfile(path_to_file)
创建
cat filename <<EOF something EOF
Python
f=open(path_to_file,"w") f.write(something) f.close()
修改
暂未接触到,以后补充
移动
Shell
mv old_file_name new_filename
Python
os.rename(old_file_name , new_filename)
拷贝
Shell
cp path_to_file new_path_to_file
Python
shutil.copy(path_to_file , new_path_to_file)
连接
与目录相同
Shell
ln -s path_to_file link_path_to_file ln path_to_file link_path_to_file
Python
os.symlink(path_to_file , link_path_to_file) os.link(path_to_file, link_path_to_file)
删除
Shell
rm path_to_file
Python
os.remove(path_to_file)
网络传输
FTP
还没尝试,待以后补充。
运行可执行程序
Shell中直接运行程序。
Python可以使用{python}os.system{/python}或者{python}subprocess{/python}模块。
os.system(command_to_excute) subprocess.check_call(command_to_excute)
subprocess模块提供多种启动程序的方式,详情参见文档《17.1. subprocess — Subprocess management》
改写方法
逐条将Shell语句翻译成Python语句。
得到的脚本看起来没有Shell脚本简洁,主要因为Shell脚本有强大的IO命令及魔术般的管道,可以写出简洁的代码。
参考
我改写后的脚本可以在如下项目中找到:
nwpc-grapes-meso-script v0.2
不再详细列出各个脚本。
