第一次python编程-FTP、执行外部命令
所做的第一个python工作是这样的,首先需要到ftp上下载一部分加密资料,然后解码,取出一些需要的变量,然后计算,计算完毕以后插值,再放到指定的ftp上去,在这里python主要做些辅助工作,实现的都是类似shell的功能,对ftp的实现采用了两种办法,一种是调用python的ftplib,一种是用系统自己的ftp。一、主控制ctr.py#!/usr/bin/env python#coding=utf-8import oscmd1="python /home/decode.py"cmd2="python /home/remerge.py"cmd3="python /home/flwtest.py"cmd4="python /home/ftpput.py"os.system(cmd1)os.system(cmd2)os.system(cmd3)os.system(cmd4) 其实很简单,import os就类似c 的include,就是加一个头文件,后面就可以调用os里面的函数,这里os.system你给他一个字符串,这里我给的都是需要顺序执行的代码。主控制需要设置定时执行,因为在linux上用,所以用的cron。cron设置方法如下
打开etc/crontab添加 30 8 * * * python /home/get.py30 9 * * *rootpython /home/ctr.py即可,数据文件可自动建立默认在home/datadircontab 添加后需要重启服务/sbin/service crond restart/sbin/service crond reload需要服务器启动即加载的话需要改 etc/rc.d/rc.local里面末尾加上/sbin/service crond start我的程序是每天运行,get.py每天8点半执行,ctr.py每天9点半执行
二、get.py是用来ftp获取数据文件的其实就是一个ftp脚本
#!/usr/bin/env python #coding=utf-8import ftplibimport osimport datetime#yestday计算昨天时间,给出格式化字符串fte=datetime.datetime.now()fte1=fte + datetime.timedelta(days = -1)print datetime.datetime.strftime( fte, '%Y%m%d')yest=datetime.datetime.strftime( fte1, '%Y%m%d')print yest#设置ftp目录dirn = '/home/DATA/2009032800/' dir1 = '/home/DATA/'+yest+'12'file1 = '2009032800000.grb1' # Define the local directory name to put data inddir="/home/datadir"# If directory doesn't exist make itif not os.path.isdir(ddir): os.mkdir(ddir)# Change the local directory to where you want to put the dataos.chdir(ddir)# login to FTP这里设置地址用户名密码f=ftplib.FTP("0.0.0.0", "user", "password")print f.getwelcome()# change the remote directoryf.cwd(dir1)f.dir()# define filename#循环拼需要ftp的文件名ii=0file0 = yest+'12'temp1=''while ii<=20: temp1=12*ii temp2=str(temp1) if ii<9: file1=file0+'0'+temp2+'.grb1' if ii==0:file1=file0+'00'+temp2+'.grb1' else: file1=file0+temp2+'.grb1' ii=ii+1 print ii print "download "+file1 f.retrbinary("RETR %s" % file1, open(file1,"wb").write,1024) print file1+"download ok"f.close()print yest+" data download end!"中间执行的一些decode、merge与主控制类似,就是调用os.system执行我的fortran程序
三、最后把数据ftp到指定服务器上这里采用的是系统的ftp与前面的不同
#!/usr/bin/env python#coding=utf-8import osos.chdir("/home/kkk/")a=os.listdir("/home/kkk/")h=open ("22.ftp","w")h.write("user kkk kkk"+ '\n')h.write("bin "+ '\n')h.write("cd /outdata/ "+ '\n')for row in a:h.write("put ") h.write(row+ '\n')#print ah.write("bye "+ '\n')cmd1="ftp -nv 1.1.1.1 <22.ftp"os.system(cmd1)cmd2="rm *"os.system(cmd2)
页:
[1]