【python编程】python引导实例参考

本文提供了Python编程的实例参考,包括文件操作、函数调用、字符串处理、系统命令执行、正则表达式使用、互联网访问等核心内容。通过具体代码示例深入探讨Python语言的应用场景与技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python引导实例参考

# -*- coding: gbk -*-
from test import sum

#python tutorial https://docs.python.org/2/tutorial/index.html
#python thread:http://www.pythonclub.org/python-basic/threading
import sys
import os
import shutil
import glob
import re
import urllib2
import random
import smtplib
from datetime import date
import zlib,gzip
#output format
import locale
#template
import time,os.path
from string import Template
#binary data unpack
import struct
import threading, zipfile
import logging
import subprocess

def test_filereadwrite():
    fp = open("worfile",'a')
    fp.write("test3")
    fp.write("test4")
    fp.close()
    try:
        f = open('myfile.txt','w+')
        s = f.readline()
        i = int(s.strip())
    except IOError as e:
        print "I/O error({0}): {1}".format(e.errno, e.strerror)
    except ValueError:
        print "Could not convert data to an integer."
    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise    

def test_func(a = 1, b = 2):
    pass


def test_strchange():
    #aStr = raw_input("please input a string:")
    aSrcStr = "admin"
    aDstStr =[]
    for i in range(5):
        aDstStr.append(chr(ord(aSrcStr[i]) + i%2))
        sys.stdout.write(aDstStr[i])

    print " "    
    print aDstStr
    test_fun()
    print u"中国"
    while True:
        pass
        break

    t = 12345, 54321, 'hello!'
    #t.append(56)
    print t,sum.sum()

def test_systemcmd():
    try:
        os.system('mkdir zouni')
        shutil.copyfile('.\\test\\sum.py', '.\\ttt\sum.py')
        print glob.glob('*.py')
        print sys.argv
        sys.stderr.write('Warning, log file not found starting a new one\n')
        sys.stdout.writelines('Warning, log file not found starting a new one')            
    except:
         print "Unexpected error:", sys.exc_info()[0]    

def test_regex():
##    >>> import re
##>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
##['foot', 'fell', 'fastest']
##>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
##'cat in the hat'
    str = re.findall(r'\bf[a-z]*','which foot or hand fell fastest')
    print str
    str = re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
    print str
    random.random()
    random.randrange(100)
    p = re.compile(r'(ab)')
    m = p.search("abcd abcf")
    print m.group()
    print m.group(1)

def test_internetacess():
##    >>> import urllib2
##    >>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
##    ...     if 'EST' in line or 'EDT' in line:  # look for Eastern Time
##    ...         print line
##
##    <BR>Nov. 25, 09:43:32 PM EST
##
##    >>> import smtplib
##    >>> server = smtplib.SMTP('localhost')
##    >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
##    ... """To: jcaesar@example.org
##    ... From: soothsayer@example.org
##    ...
##    ... Beware the Ides of March.
##    ... """)
##    >>> server.quit()
    for line in urllib2.urlopen('http://www.163.com'):
        #print line
        #http://bbs.chinaunix.net/thread-1163613-1-1.html
        if '杭研监控' in line or 'EDT' in line:  # look for Eastern Time
            print line
def test_filezip():            
    content = "Lots of content here"
    with gzip.open('.\\test\\testc.gz', 'wb') as f:
        f.write(content)

test_filezip()    



class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile
    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print 'Finished background zip of: ', self.infile

def test_thread():
    background = AsyncZip('.\\test\\sum.py', '.\\test\\myarchive.zip')
    background.start()
    print 'The main program continues to run in foreground.\n'

    background.join()    # Wait for the background task to finish
    print 'Main program waited until background was done.'

def test_log():
    logging.debug('Debugging information')
    logging.info('Informational message')
    logging.warning('Warning:config file %s not found', 'server.conf')
    logging.error('Error occurred')
    logging.critical('Critical error -- shutting down')
    print  sys.stderr.readlines()

def test_shellcmds():
    #python中执行shell命令
    subprocess.call('mkdir hello', shell=True)

test_shellcmds()    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值