简明Python教程之编写一个Pyhton脚本

三种方案的正确代码:

方案一:

 

#coding=utf-8
import os
import time
source = ['d:\\testpy1','d:\\testpy2']
target_dir = 'd:\\testpy\\'
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "zip -qr \"%s\" \"%s\"" % (target,'" "'.join(source))
str = 'sucessful backup to'
if os.system(zip_command) == 0:
    #print str,target#Pycharm正常显示中文
    print str.decode('utf-8').encode('gbk'),target#系统控制台正确显示中文
else:
    print 'Backup Failed'

 

 

 

方案二:

 

 

 

#coding=utf-8
import os
import time
source = ['d:\\testpy1', 'd:\\testpy2']
target_dir = 'd:\\testpy\\'
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
if not os.path.exists(today):
    os.mkdir(today)
print 'Successfully created directory', today
target = today + os.sep + now + '.zip'
zip_command = "zip -qr \"%s\" \"%s\"" % (target, '" "'.join(source))
if os.system(zip_command) == 0:
    print 'Successful backup to', target

 

方案3:

 

#coding=utf-8
import os
import time
source = ['d:\\testpy1','d:\\testpy2']
target_dir = 'd:\\testpy\\'
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
comment = raw_input('Enter a comment --> ')
if len(comment) == 0:
    target = today + os.sep + now + '.zip'
else:
    target = today + os.sep + now + '_' +\
comment.replace(' ', '_') + '.zip'
if not os.path.exists(today):#条件为false时执行下一句
    os.mkdir(today)
print 'Successfully created directory', today
zip_command = "zip -qr \"%s\" \"%s\"" % (target, '" "'.join(source))
if os.system(zip_command) == 0:
    print 'Successful backup to', target
else:
    print 'Backup FAILED'

 

 

 

 

 

期间遇到字符编码的问题:

情况一:Pycharm控制台输出中文汉字为乱码(即print中要输出字符串的语句)
解决方案:在代码首部加入注释#coding=utf-8


情况二:控制台输出中文乱码
解决方案:
str = 'Successful backup to成功'
print str.decode('utf-8').encode('gbk')#, target
这里gbk和cp936都可以

遗留问题:
Pycharm调用os.system命令时系统提示错误显示为乱码
如zip不是内部或外部命令。

CP936与GBK、GB2312、GB18030区别
http://blog.wuliaoa.com/?p=503
字符编码说明
http://www.cnblogs.com/evening/archive/2012/04/19/2457440.html
utf-8转gbk
http://www.cnblogs.com/sunshuhai/p/6242275.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值