pythonretr
importftplib
path='c:/user/pcwuyu/desktop/1c0/'
l=[]
defls_filter(line):
ll=line.split()
ifll[5]=='Jan'andll[6]=='9'andll[7]>'14:30'andll[7]<'15:30':
ifll[8]!='.'andll[8]!='..':
l.append(ll[8])
returnll[8]
ftp=ftplib.FTP('127.0.0.1')
ftp.login('root','password')
ftp.cwd('/mnt/1c0')
ftp.set_pasv(False)
fs=ftp.retrlines('LIST',ls_filter)
foriinl:
ftp.retrbinary('RETR'+i,open(path+i,'wb').write)
ftp.quit()
一个简单的例子,下载1月9日14:30~15:30的文件
❷ 如何在Python中使用FTP
from ftplip import FTP # 首先要引入 ftplib 这个库
# 接着,这是我自定义的几个用于操作 ftp 的函数,def 后面跟的是自定义函数名,函数体内FTP 相关的语句和函数来自上面 import 那个包,你自己体会吧:
# 初始化 FTP 连接
def ftp_open(HOST,PORT,USERNAME,PASSWORD):
ftp=FTP()
ftp.set_debuglevel(2)
ftp.connect(host=HOST,port=PORT)
ftp.login(USERNAME,PASSWORD)
return ftp
# 关闭 FTP 连接
def ftp_close(ftp):
ftp.set_debuglevel(0)
ftp.quit()
# 文件上传函数,filename 可以是windows 格式包含全路径的文件
def ftp_up(ftp,filename):
#print(ftp.getwelcome())
#ftp.cwd('xxx/www')
file_handler=open(filename,'rb')
ftp.storbinary('STOR %s' % os.path.basename(filename),file_handler)
file_handler.close()
print('FTP up OK.')
# 文件下载函数,filename 可以是windows 格式包含全路径的文件
def ftp_down(ftp,filename):
#print(ftp.getwelcome())
#ftp.cwd('xxx/www')
file_handler=open(filename,'wb')
ftp.retrbinary('RETR %s' % os.path.basename(filename),file_handler)
file_handler.close()
print('FTP down OK.')
❸ Python,if 条件 总是不执行 python pop.py stat 无论什么指令都quit为什么
下面是你的赋值语句
action =""
然后下面的判断条件都不成立
if action == 'stat':
elif action == 'list':
elif action =='retr':
无奈只有这个成立else:
判断条件只能走else语句,就只能执行pp.quit()啦
❹ 怎么把Python ftplib 中下载文件名写成函数
拼装后作为参数:
cmd = 'RETR ' + name()
frp.retrbinary(cmd, file_handel, bufsize)
❺ python 收取邮件都是乱码。
一般邮件在传输的时候都会被编码,图中的是base64编码的特征,这类编码是可逆的,只需要进行base64解码即可,python有个base64模块,可以用来编码和解码。
❻ python poplib 模块 连接gmail出错 试过163 就没问题 这是什么原因
给你一个发送邮件,接收邮件,并且根据邮件头计算邮件发送,接收时间差的公共代码
#!/usr/bin/envpython
#coding=utf-8
importsys
importtime
importpoplib
importsmtplib
fromdatetimeimportdatetime
importemail
fromemail.parserimportParser
fromemail.headerimportdecode_header
fromemail.utilsimportparseaddr
fromemail.mime.textimportMIMEText
importre
importpyodbc
defremove_values_from_list(the_list,val):
whilevalinthe_list:
the_list.remove(val)
#邮件发送函数
defsend_mail(mail_host,mail_user,mail_pass,mail_postfix,to_list,sub,content):
me=""+""+mail_user+"@"+mail_postfix+""
#printme
msg=MIMEText(content,_subtype='plain')
msg['Subject']=sub
msg['From']=me
msg['To']=";".join(to_list)#将收件人列表以‘;’分隔
try:
server=smtplib.SMTP()
server.connect(mail_host)#连接服务器
server.login(mail_user,mail_pass)#登录操作
server.sendmail(me,to_list,msg.as_string())
server.close()
returnTrue
exceptException,e:
#printe
returnFalse
returnFalse
#邮件接收函数
defaccpet_mail(accpet_host,accpet_user,accpet_pass):
mail_list=[]
#printaccpet_host
#print"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
try:
p=poplib.POP3(accpet_host)
p.user(accpet_user)
p.pass_(accpet_pass)
(mail_count,mail_total_size)=p.stat()#返回一个元组:(邮件数,邮件尺寸)
foriinrange(mail_count):
mail_map={}
#邮件从1开始读取,retr方法返回一个元组:(状态信息,邮件,邮件尺寸)
status_info,email_info,email_size=p.retr(str(i+1))
#printdecode_header(email.message_from_string(str(email_info)))[0][0]
#printemail.message_from_string(str(email_info))
message={}
last_email_item,append_flag="",True
#printstr(decode_header(email_info)[0][0])
remove_values_from_list(email_info,'')
forj,email_iteminenumerate(email_info):
ifj==len(email_info)-1:
message["Content"]=email_item
break
email_item_list="".join(email_item.split(" ")).split(":")
iflen(email_item_list)!=2:
ifappend_flag==True:
message[last_email_item]=message.get(last_email_item)+email_item_list[0]
#printemail_item_list[0]
else:
ifemail_item_list[0]inmessage:
append_flag=False
continue
message[email_item_list[0]]=email_item_list[1]
last_email_item=email_item_list[0]
if"Subject"notinmessageor"Content"notinmessage:
p.dele(str(i+1))
continue
#printi+1,message.get("Subject"),message.get("Content")
content_match_list=re.findall(r"Thesendingtime",message.get("Content"))
subject_match_list=re.findall(r"MAILVIEW",message.get("Subject"))
ifsubject_match_list==[]orcontent_match_list==[]:
p.dele(str(i+1))
#printi+1,message.get("Subject"),message.get("Content")
#print"2:"+str(email_info)
continue
#printstr(i+1)
content_list=message.get("Content").split("#")
send_list=content_list[0].split(":")
#print"send_time"+str(datetime.strptime(send_list[1],'%Y%m%d%H%M%S'))
#mail_map["send_time"]=str(datetime.strptime(send_list[1],'%Y%m%d%H%M%S'))
#mail_map["recive_time"]=str(datetime.strptime(message.get("Date"),'%a,%d%b%Y%H:%M:%S+0800'))
sr_list=content_list[1].split("@")
from_list=sr_list[0].split(":")
to_list=sr_list[1].split(":")
#printfrom_list[0]+":"+from_list[1]
mail_map[from_list[0]]=from_list[1]
#printto_list[0]+":"+to_list[1]
mail_map[to_list[0]]=to_list[1]
#print"recive_time:"+str(datetime.strptime(message.get("Date"),'%a,%d%b%Y%H:%M:%S+0800'))
#Mon,30Mar201514:20:58+0800'%a,%d%b%Y%H:%M:%S+0800'
#mail_map["send_time"]=str(datetime.strptime(message.get("Date"),'%a,%d%b%Y%H:%M:%S+0800'))
#从字符串读取信息-->解密邮件头-->字符串取[0][0]-->以" "分组-->取第一个-->替换字符串"Fromnobody"为空-->格式化为日期格式-->得到接收时间
#mail_map["recive_time"]=str(datetime.strptime(str(decode_header(email.message_from_string(str(email_info)))[0][0]).split(" ")[0].replace("Fromnobody",""),'%a%b%d%H:%M:%S%Y'))
mail_map["send_time"]=str(time.strftime("%Y-%m-%d%H:%M:%S",time.localtime(time.mktime(email.utils.parsedate(message.get('Date'))))))
receive_time_list=message.get('Received').split(";")
mail_map["recive_time"]=str(datetime.strptime(receive_time_list[len(receive_time_list)-1].replace("(CST)","").lstrip(),'%a,%d%b%Y%H:%M:%S+0800'))
#printmessage
#print"send_time:%s"%mail_map.get('send_time')
#print"recive_time:%s"%mail_map.get('recive_time')
#print"----------------------------------------------------------------"
mail_list.append(mail_map)
p.dele(str(i+1))
p.quit()
returnmail_list
exceptpoplib.error_proto,e:
#print"Loginfailed:",e
p.quit()
returnmail_list
#sys.exit(1)
returnmail_list
#运行当前文件时,执行sendmail和accpet_mail函数
if__name__=="__main__":
'''
mailto_list,mail_send_host=['[email protected]'],"smtp.gacfiatauto.com"
mail_send_user,mail_send_pass,mail_send_postfix="test","GACFiat1234","gacfiatauto.com"
NOW=datetime.now()
now_str=datetime.strftime(NOW,'%Y%m%d%H%M%S')
sub="MAILVIEW"+now_str
content="Thesendingtime:"+now_str+"#from_mail:JV@to_mail:126"
send_mail(mail_send_host,mail_send_user,mail_send_pass,mail_send_postfix,mailto_list,sub,content)
#accpet_host,accpet_user,accpet_pass='pop.126.com','gacfiat','fiat100?'
accpet_host,accpet_user,accpet_pass='pop3.gacfiatauto.com','test','GACFiat1234'
accpet_mail(accpet_host,accpet_user,accpet_pass)
'''
DB2_HOST='10.27.95.30'
DB2_PORT='50000'
DB2_DB='db2s'
DB2_USER='db2admin'
DB2_PWD='fiat100?'
dsn="driver={IBMDB2ODBCDRIVER};database=%s;hostname=%s;port=%s;protocol=tcpip;"%(DB2_DB,DB2_HOST,DB2_PORT)
conn=pyodbc.connect(dsn+"uid="+DB2_USER+";pwd="+DB2_PWD+";");
cursor=conn.cursor()
cursor.execute("select*fromkernel.mail_property")
row=cursor.fetchone()
property_list=[]
#1获取要发送和接收邮件的属性信息
whilerow:
(from_mail,from_protocol,from_address,from_host,auth_flag,from_port,from_user,from_password,to_mail,to_protocol,to_address,to_host,to_port,to_user,to_password,is_current,t2)=(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10],row[11],row[12],row[13],row[14],row[15],row[16])
row=cursor.fetchone()
ifis_current=="1":#andfrom_mail=='126'andto_mail=="JV":
property_list.append((from_mail,from_protocol,from_address,from_host,auth_flag,from_port,from_user,from_password,to_mail,to_protocol,to_address,to_host,to_port,to_user,to_password,is_current,t2))
cursor.close()
#2发送邮件
forpropertyinproperty_list:
(from_mail,from_protocol,from_address,from_host,auth_flag,from_port,from_user,from_password,to_mail,to_protocol,to_address,to_host,to_port,to_user,to_password,is_current,t2)=property
mailto_list=[to_address]
mail_send_host=from_host
mail_send_user=from_user
mail_send_pass=from_password
mail_send_postfix=from_host.replace(from_protocol+".","")
NOW=datetime.now()
now_str=datetime.strftime(NOW,'%Y%m%d%H%M%S')
sub="MAILVIEW"+now_str
content="Thesendingtime:"+now_str+"#from_mail:"+from_mail+"@to_mail:"+to_mail
#printmail_send_host
send_resp=send_mail(mail_send_host,mail_send_user,mail_send_pass,mail_send_postfix,mailto_list,sub,content)
ifsend_resp:#如果发送失败,再尝试发送一次
continue
else:
#print'sendfail,sendagain.'
send_mail(mail_send_host,mail_send_user,mail_send_pass,mail_send_postfix,mailto_list,sub,content)
#3接收邮件
forpropertyinproperty_list:
(from_mail,from_protocol,from_address,from_host,auth_flag,from_port,from_user,from_password,to_mail,to_protocol,to_address,to_host,to_port,to_user,to_password,is_current,t2)=property
accpet_host=to_host
accpet_user=to_user
accpet_pass=to_password
starttime=datetime.now()
#printaccpet_host
mail_list=accpet_mail(accpet_host,accpet_user,accpet_pass)
#4添加邮件记录信息到DB2数据库中
insert_sql="insertintokernel.mail_data(from_mail,send_time,to_mail,recive_time)values"
fori,mailinenumerate(mail_list):
from_mail,send_time,to_mail,recive_time=mail['from_mail'],mail['send_time'],mail['to_mail'],mail['recive_time']
#printsend_time,from_mail,to_mail,recive_time
insert_sql=insert_sql+"('%s',to_date('%s','yyyy-mm-ddhh24:mi:ss'),'%s',to_date('%s','yyyy-mm-ddhh24:mi:ss')),"%(from_mail,send_time,to_mail,recive_time)
ifi==len(mail_list)-1:
insert_sql=insert_sql[:len(insert_sql)-1]
endtime=datetime.now()
message='开始时间:%s,总共耗时:%ss'%(starttime,(endtime-starttime).seconds)
#printmessage
ifmail_list!=Noneandmail_list!=[]:
#printinsert_sql
cursor=conn.cursor()
cursor.execute(insert_sql)
cursor.commit()
cursor.close()
#sys.exit(1)
❼ python 检测FTP目录是否为空
ftp相关命令操作
ftp.cwd(pathname) #设置FTP当前操作的路径
ftp.dir() #显示目录下文件信息
ftp.nlst() #获取目录下的文件
ftp.mkd(pathname) #新建远程目录
ftp.pwd() #返回当前所在位置
ftp.rmd(dirname) #删除远程目录
ftp.delete(filename) #删除远程文件
ftp.rename(fromname, toname)#将fromname修改名称为toname。
ftp.storbinaly("STOR filename.txt",file_handel,bufsize) #上传目标文件
ftp.retrbinary("RETR filename.txt",file_handel,bufsize)#下载FTP文件
❽ python图像处理代码,望大神详细解释。越详细越好
#初始化一个矩形np.max(marks)+1行,3列,默认值为0
colorTab=np.zeros((np.max(marks)+1,3))
#遍历数组,给每行的3列赋值,就是RGB颜色值,8位的
foriinrange(len(colorTab)):
aa=np.random.uniform(0,255)
bb=np.random.uniform(0,255)
cc=np.random.uniform(0,255)
colorTab[i]=np.array([aa,bb,cc],np.uint8)
#初始化另一个跟img图像形状大小一样的图像,一副黑色图像
bgrImage=np.zeros(img.shape,np.uint8)
#遍历marks形状的行列
foriinrange(marks.shape[0]):
forjinrange(marks.shape[1]):
index=marks[i][j]
#判断是不是区域与区域之间的分界,如果是边界(-1),则使用白色显示
ifindex==-1:
bgrImage[i][j]=np.array([255,255,255])#像素点设置位白色
else:
bgrImage[i][j]=colorTab[index]#像素点设置位上边随机生成的颜色值
#显示处理后的图像图像
cv2.imshow('AfterColorFill',bgrImage)
#总结,先生成一个跟marks相同数量的row*col的一张颜色表,然后创建一个跟marks相同大小的一副黑色图像
#最后对黑色图像画出白色边界和内部随机彩色像素值
❾ python怎么识别图片中每个线的基本形状
轮廓搜索
Cv2的方法。findContours用于查找轮廓。代码示例如下:
Cr、t = cv2。cv2 findContours (b。retr_tree cv2.chain_approx_simple) #
第三个参数定义了轮廓的近似方式
在上述函数的参数中,第一个参数是二值化矩阵,第二个参数是获得轮廓的方式,第三个参数是定义轮廓的近似方式。
搜索大纲
Cv2方法。FindContours用于查找contours。代码示例如下:
Cr t等于cv2。Cv2 findContours (b. retr_tree Cv2 .chain_approx_simple) #
第三个参数定义了轮廓的近似方式
上述函数的参数中,第一个参数是二值化矩阵,第二个参数是获取轮廓的方式,第三个参数是定义轮廓的近似方式。
❿ 怎样使用Python图像处理
Python图像处理是一种简单易学,功能强大的解释型编程语言,它有简洁明了的语法,高效率的高层数据结构,能够简单而有效地实现面向对象编程,下文进行对Python图像处理进行说明。
当然,首先要感谢“恋花蝶”,是他的文章“用Python图像处理 ” 帮我坚定了用Python和PIL解决问题的想法,对于PIL的一些介绍和基本操作,可以看看这篇文章。我这里主要是介绍点我在使用过程中的经验。
PIL可以对图像的颜色进行转换,并支持诸如24位彩色、8位灰度图和二值图等模式,简单的转换可以通过Image.convert(mode)函数完 成,其中mode表示输出的颜色模式。例如''L''表示灰度,''1''表示二值图模式等。
但是利用convert函数将灰度图转换为二值图时,是采用固定的阈 值127来实现的,即灰度高于127的像素值为1,而灰度低于127的像素值为0。为了能够通过自定义的阈值实现灰度图到二值图的转换,就要用到 Image.point函数。
深度剖析Python语法功能
深度说明Python应用程序特点
对Python数据库进行学习研究
Python开发人员对Python经验之谈
对Python动态类型语言解析
Image.point函数有多种形式,这里只讨论Image.point(table, mode),利用该函数可以通过查表的方式实现像素颜色的模式转换。其中table为颜色转换过程中的映射表,每个颜色通道应当有256个元素,而 mode表示所输出的颜色模式,同样的,''L''表示灰度,''1''表示二值图模式。
可见,转换过程的关键在于设计映射表,如果只是需要一个简单的箝位值,可以将table中高于或低于箝位值的元素分别设为1与0。当然,由于这里的table并没有什么特殊要求,所以可以通过对元素的特殊设定实现(0, 255)范围内,任意需要的一对一映射关系。
示例代码如下:
import Image # load a color image im = Image.open(''fun.jpg'') # convert to grey level image Lim = im.convert(''L'') Lim.save(''fun_Level.jpg'') # setup a converting table with constant threshold threshold = 80 table = [] for i in range(256): if i < threshold: table.append(0) else: table.append(1) # convert to binary image by the table bim = Lim.point(table, ''1'') bim.save(''fun_binary.jpg'')
IT部分通常要完成的任务相当繁重但支撑这些工作的资源却很少,这已经成为公开的秘密。任何承诺提高编码效率、降低软件总成本的IT解决方案都应该进行 周到的考虑。Python图像处理所具有的一个显着优势就是可以在企业的软件创建和维护阶段节约大量资金,而这两个阶段的软件成本占到了软件整个生命周期中总成本 的50%到95%。
Python清晰可读的语法使得软件代码具有异乎寻常的易读性,甚至对那些不是最初接触和开发原始项目的程序员都 能具有这样的强烈感觉。虽然某些程序员反对在Python代码中大量使用空格。
不过,几乎人人都承认Python图像处理的可读性远胜于C或者Java,后两 者都采用了专门的字符标记代码块结构、循环、函数以及其他编程结构的开始和结束。提倡Python的人还宣称,采用这些字符可能会产生显着的编程风格差 异,使得那些负责维护代码的人遭遇代码可读性方面的困难。转载