`
收藏列表
标题 标签 来源
python date time python的time和date处理
1. # handling date/time data
   2. # Python23 tested vegaseat 3/6/2005
   3.
   4. import time
   5.
   6. print "List the functions within module time:"
   7. for funk in dir(time):
   8. print funk
   9.
  10. print time.time(), "seconds since 1/1/1970 00:00:00"
  11. print time.time()/(60*60*24), "days since 1/1/1970"
  12.
  13. # time.clock() gives wallclock seconds, accuracy better than 1 ms
  14. # time.clock() is for windows, time.time() is more portable
  15. print "Using time.clock() = ", time.clock(), "seconds since first call to clock()"
  16. print "\nTiming a 1 million loop 'for loop' ..."
  17. start = time.clock()
  18. for x in range(1000000):
  19. y = x # do something
  20. end = time.clock()
  21. print "Time elapsed = ", end - start, "seconds"
  22.
  23. # create a tuple of local time data
  24. timeHere = time.localtime()
  25. print "\nA tuple of local date/time data using time.localtime():"
  26. print "(year,month,day,hour,min,sec,weekday(Monday=0),yearday,dls-flag)"
  27. print timeHere
  28.
  29. # extract a more readable date/time from the tuple
  30. # eg. Sat Mar 05 22:51:55 2005
  31. print "\nUsing time.asctime(time.localtime()):", time.asctime(time.localtime())
  32. # the same results
  33. print "\nUsing time.ctime(time.time()):", time.ctime(time.time())
  34. print "\nOr using time.ctime():", time.ctime()
  35.
  36. print "\nUsing strftime():"
  37. print "Day and Date:", time.strftime("%a %m/%d/%y", time.localtime())
  38. print "Day, Date :", time.strftime("%A, %B %d, %Y", time.localtime())
  39. print "Time (12hr) :", time.strftime("%I:%M:%S %p", time.localtime())
  40. print "Time (24hr) :", time.strftime("%H:%M:%S", time.localtime())
  41. print "DayMonthYear:",time.strftime("%d%b%Y", time.localtime())
  42.
  43. print
  44.
  45. print "Start a line with this date-time stamp and it will sort:",\
  46. time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
  47.
  48. print
  49.
  50. def getDayOfWeek(dateString):
  51. # day of week (Monday = 0) of a given month/day/year
  52. t1 = time.strptime(dateString,"%m/%d/%Y")
  53. # year in time_struct t1 can not go below 1970 (start of epoch)!
  54. t2 = time.mktime(t1)
  55. return(time.localtime(t2)[6])
  56.
  57. Weekday = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
  58. 'Friday', 'Saturday', 'Sunday']
  59.
  60. # sorry about the limitations, stay above 01/01/1970
  61. # more exactly 01/01/1970 at 0 UT (midnight Greenwich, England)
  62. print "11/12/1970 was a", Weekday[getDayOfWeek("11/12/1970")]
  63.
  64. print
  65.
  66. print "Calculate difference between two times (12 hour format) of a day:"
  67. time1 = raw_input("Enter first time (format 11:25:00AM or 03:15:30PM): ")
  68. # pick some plausible date
  69. timeString1 = "03/06/05 " + time1
  70. # create a time tuple from this time string format eg. 03/06/05 11:22:00AM
  71. timeTuple1 = time.strptime(timeString1, "%m/%d/%y %I:%M:%S%p")
  72.
  73. #print timeTuple1 # test eg. (2005, 3, 6, 11, 22, 0, 5, 91, -1)
  74.
  75. time2 = raw_input("Enter second time (format 11:25:00AM or 03:15:30PM): ")
  76. # use same date to stay in same day
  77. timeString2 = "03/06/05 " + time2
  78. timeTuple2 = time.strptime(timeString2, "%m/%d/%y %I:%M:%S%p")
  79.
  80. # mktime() gives seconds since epoch 1/1/1970 00:00:00
  81. time_difference = time.mktime(timeTuple2) - time.mktime(timeTuple1)
  82. #print type(time_difference) # test <type 'float'>
  83. print "Time difference = %d seconds" % int(time_difference)
  84. print "Time difference = %0.1f minutes" % (time_difference/60.0)
  85. print "Time difference = %0.2f hours" % (time_difference/(60.0*60))
  86.
  87. print
  88.
  89. print "Wait one and a half seconds!"
  90. time.sleep(1.5)
  91. print "The end!"
ping ping 的python源码
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""ping.py

ping.py uses the ICMP protocol's mandatory ECHO_REQUEST
datagram to elicit an ICMP ECHO_RESPONSE from a
host or gateway.

Copyright (C) 2004 - Lars Strand <lars strand at gnist org>;

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

Must be running as root, or write a suid-wrapper. Since newer *nix
variants, the kernel ignores the set[ug]id flags on #! scripts for
security reasons

RFC792, echo/reply message:

  0                   1                   2                   3
  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|     Type      |     Code      |          Checksum             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|           Identifier          |        Sequence Number        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|     Data ...
+-+-+-+-+-


TODO:
- do not create socket inside 'while' (but if not: ipv6 won't work)
- add support for broadcast/multicast
- add support for own payload string

CHANGELOG:
DONE -->; bugfix from Filip Van Raemdonck mechanix debian org
DONE -->; add more support for modules (raise instead of sys.exit)
DONE -->; locale func names
DONE -->; package def
DONE -->; some code cleanup

"""

import sys
import os
import struct
import array
import time
import select
import binascii
import math
import getopt
import string
import socket

# total size of data (payload)
ICMP_DATA_STR = 56  

# initial values of header variables
ICMP_TYPE = 8
ICMP_TYPE_IP6 = 128
ICMP_CODE = 0
ICMP_CHECKSUM = 0
ICMP_ID = 0
ICMP_SEQ_NR = 0

# Package definitions.
__program__   = 'ping'
__version__   = '0.5a'
__date__      = '2004/15/12'
__author__    = 'Lars Strand <lars at unik no>;'
__licence__   = 'GPL'
__copyright__ = 'Copyright (C) 2004 Lars Strand'

def _construct(id, size, ipv6):
    """Constructs a ICMP echo packet of variable size
    """

    # size must be big enough to contain time sent
    if size < int(struct.calcsize("d")):
        _error("packetsize to small, must be at least %d" % int(struct.calcsize("d")))
   
    # construct header
    if ipv6:
        header = struct.pack('BbHHh', ICMP_TYPE_IP6, ICMP_CODE, ICMP_CHECKSUM, \
                             ICMP_ID, ICMP_SEQ_NR+id)
    else:
        header = struct.pack('bbHHh', ICMP_TYPE, ICMP_CODE, ICMP_CHECKSUM, \
                             ICMP_ID, ICMP_SEQ_NR+id)

    # if size big enough, embed this payload
    load = "-- IF YOU ARE READING THIS YOU ARE A NERD! --"
   
    # space for time
    size -= struct.calcsize("d")

    # construct payload based on size, may be omitted :)
    rest = ""
    if size > len(load):
        rest = load
        size -= len(load)

    # pad the rest of payload
    rest += size * "X"

    # pack
    data = struct.pack("d", time.time()) + rest
    packet = header + data          # ping packet without checksum
    checksum = _in_cksum(packet)    # make checksum

    # construct header with correct checksum
    if ipv6:
        header = struct.pack('BbHHh', ICMP_TYPE_IP6, ICMP_CODE, checksum, \
                             ICMP_ID, ICMP_SEQ_NR+id)
    else:
        header = struct.pack('bbHHh', ICMP_TYPE, ICMP_CODE, checksum, ICMP_ID, \
                             ICMP_SEQ_NR+id)

    # ping packet *with* checksum
    packet = header + data

    # a perfectly formatted ICMP echo packet
    return packet

def _in_cksum(packet):
    """THE RFC792 states: 'The 16 bit one's complement of
    the one's complement sum of all 16 bit words in the header.'

    Generates a checksum of a (ICMP) packet. Based on in_chksum found
    in ping.c on FreeBSD.
    """

    # add byte if not dividable by 2
    if len(packet) & 1:              
        packet = packet + '\0'

    # split into 16-bit word and insert into a binary array
    words = array.array('h', packet)
    sum = 0

    # perform ones complement arithmetic on 16-bit words
    for word in words:
        sum += (word & 0xffff)

    hi = sum >> 16
    lo = sum & 0xffff
    sum = hi + lo
    sum = sum + (sum >> 16)
   
    return (~sum) & 0xffff # return ones complement

def pingNode(alive=0, timeout=1.0, ipv6=0, number=sys.maxint, node=None, \
             flood=0, size=ICMP_DATA_STR):
    """Pings a node based on input given to the function.
    """

    # if no node, exit
    if not node:
        _error("")

    # if not a valid host, exit
    if ipv6:
        if socket.has_ipv6:
            try:
                info, port = socket.getaddrinfo(node, None)
                host = info[4][0]
                # do not print ipv6 twice if ipv6 address given as node
                if host == node:
                    noPrintIPv6adr = 1
            except:
                _error("cannot resolve %s: Unknow host" % node)
        else:
            _error("No support for IPv6 on this plattform")
    else:    # IPv4
        try:
            host = socket.gethostbyname(node)
        except:
            _error("cannot resolve %s: Unknow host" % node)

    # trying to ping a network?
    if not ipv6:
        if int(string.split(host, ".")[-1]) == 0:
            _error("no support for network ping")

    # do some sanity check
    if number == 0:
        _error("invalid count of packets to transmit: '%s'" % str(a))
    if alive:
        number = 1

    # Send the ping(s)
    start = 1; mint = 999; maxt = 0.0; avg = 0.0
    lost = 0; tsum = 0.0; tsumsq = 0.0

    # tell the user what we do
    if not alive:
        if ipv6:
            # do not print the ipv6 twice if ip adress given as node
            # (it can be to long in term window)
            if noPrintIPv6adr == 1:
                # add 40 (header) + 8 (icmp header) + payload
                print "PING %s : %d data bytes (40+8+%d)" % (str(node), \
                                                             40+8+size, size)
            else:
                # add 40 (header) + 8 (icmp header) + payload
                print "PING %s (%s): %d data bytes (40+8+%d)" % (str(node), \
                                                                 str(host), 40+8+size, size)
        else:
            # add 20 (header) + 8 (icmp header) + payload
            print "PING %s (%s): %d data bytes (20+8+%d)" % (str(node), str(host), \
                                                             20+8+size, size)
        
    # trap ctrl-d and ctrl-c
    try:
        
        # send the number of ping packets as given
        while start <= number:
            lost += 1 # in case user hit ctrl-c
            
            # create the IPv6/IPv4 socket
            if ipv6:
                # can not create a raw socket if not root or setuid to root
                try:
                    pingSocket = socket.socket(socket.AF_INET6, socket.SOCK_RAW, \
                                               socket.getprotobyname("ipv6-icmp"))
                except socket.error, e:
                    print "socket error: %s" % e
                    _error("You must be root (uses raw sockets)" % os.path.basename(sys.argv[0]))
                    
            # IPv4
            else:
                # can not create a raw socket if not root or setuid to root
                try:
                    pingSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, \
                                               socket.getprotobyname("icmp"))
                except socket.error, e:
                    print "socket error: %s" % e
                    _error("You must be root (%s uses raw sockets)" % os.path.basename(sys.argv[0]))
               
            packet = _construct(start, size, ipv6) # make a ping packet

            # send the ping
            try:
                pingSocket.sendto(packet,(node,1))
            except socket.error, e:
                _error("socket error: %s" % e)

            # reset values
            pong = ""; iwtd = []

            # wait until there is data in the socket
            while 1:
                # input, output, exceptional conditions
                iwtd, owtd, ewtd = select.select([pingSocket], [], [], timeout)
                break # no data and timout occurred

            # data on socket - this means we have an answer
            if iwtd:  # ok, data on socket
                endtime = time.time()  # time packet received
                # read data (we only need the header)
                pong, address = pingSocket.recvfrom(size+48)
                lost -= 1 # in case user hit ctrl-c

                # examine packet
                # fetch TTL from IP header
                if ipv6:
                    # since IPv6 header and any extension header are never passed
                    # to a raw socket, we can *not* get hoplimit field..
                    # I hoped that a socket option would help, but it's not
                    # supported:
                    #   pingSocket.setsockopt(IPPROTO_IPV6, IPV6_RECVHOPLIMIT, 1)
                    # so we can't fetch hoplimit..

                    # fetch hoplimit
                    #rawPongHop = struct.unpack("c", pong[7])[0]

                    # fetch pong header
                    pongHeader = pong[0:8]
                    pongType, pongCode, pongChksum, pongID, pongSeqnr = \
                              struct.unpack("bbHHh", pongHeader)

                    # fetch starttime from pong
                    starttime = struct.unpack("d", pong[8:16])[0]

                # IPv4
                else:
                    # time to live
                    rawPongHop = struct.unpack("s", pong[8])[0]

                    # convert TTL from 8 bit to 16 bit integer
                    pongHop = int(binascii.hexlify(str(rawPongHop)), 16)

                    # fetch pong header
                    pongHeader = pong[20:28]
                    pongType, pongCode, pongChksum, pongID, pongSeqnr = \
                              struct.unpack("bbHHh", pongHeader)

                    # fetch starttime from pong
                    starttime = struct.unpack("d", pong[28:36])[0]

                # valid ping packet received?
                if not pongSeqnr == start:
                    pong = None

            # NO data on socket - timeout waiting for answer
            if not pong:
                if alive:
                    print "no reply from %s (%s)" % (str(node), str(host))
                else:
                    print "ping timeout: %s (icmp_seq=%d) " % (host, start)

                # do not wait if just sending one packet
                if number != 1 and start < number:
                    time.sleep(flood ^ 1)
                start += 1
                continue  # lost a packet - try again

            triptime  = endtime - starttime # compute RRT
            tsum     += triptime            # triptime for all packets (stddev)
            tsumsq   += triptime * triptime # triptime^2  for all packets (stddev)

            # compute statistic
            maxt = max ((triptime, maxt))
            mint = min ((triptime, mint))

            if alive:
                print str(node) + " (" + str(host) +") is alive"
            else:
                if ipv6:
                    # size + 8 = payload + header
                    print "%d bytes from %s: icmp_seq=%d time=%.5f ms" % \
                          (size+8, host, pongSeqnr, triptime*1000)
                else:
                    print "%d bytes from %s: icmp_seq=%d ttl=%s time=%.5f ms" % \
                          (size+8, host, pongSeqnr, pongHop, triptime*1000)

            # do not wait if just sending one packet
            if number != 1 and start < number:
                # if flood = 1; do not sleep - just ping               
                time.sleep(flood ^ 1) # wait before send new packet

            # the last thing to do is update the counter - else the value
            # (can) get wrong when computing summary at the end (if user
            # hit ctrl-c when pinging)
            start += 1
            # end ping send/recv while

    # if user ctrl-d or ctrl-c
    except (EOFError, KeyboardInterrupt):
        # if user disrupts ping, it is most likly done before
        # the counter get updates - if do not update it here, the
        # summary get all wrong.
        start += 1
        pass

    # compute and print som stats
    # stddev computation based on ping.c from FreeBSD
    if start != 0 or lost > 0:  # do not print stats if 0 packet sent
        start -= 1              # since while is '<='
        avg = tsum / start      # avg round trip
        vari = tsumsq / start - avg * avg
        # %-packet lost
        if start == lost:
            plost = 100
        else:
            plost = (lost/start)*100

        if not alive:
            print "\n--- %s ping statistics ---" % node
            print "%d packets transmitted, %d packets received, %d%% packet loss" % \
                  (start, start-lost, plost)
            # don't display summary if 100% packet-loss
            if plost != 100:
                print "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms" % \
                      (mint*1000, (tsum/start)*1000, maxt*1000, math.sqrt(vari)*1000)

    pingSocket.close()
   
def _error(err):
    """Exit if running standalone, else raise an exception
    """

    if __name__ == '__main__':
        print "%s: %s" % (os.path.basename(sys.argv[0]), str(err))
        print "Try `%s --help' for more information." % os.path.basename(sys.argv[0])
        sys.exit(1)
    else:
        raise Exception, str(err)
   
def _usage():
    """Print usage if run as a standalone program
    """
    print """usage: %s [OPTIONS] HOST
Send ICMP ECHO_REQUEST packets to network hosts.

Mandatory arguments to long options are mandatory for short options too.
  -c, --count=N    Stop after sending (and receiving) 'N' ECHO_RESPONSE
                   packets.
  -s, --size=S     Specify the number of data bytes to be sent. The default
                   is 56, which translates into 64 ICMP data bytes when
                   combined with the 8 bytes of ICMP header data.
  -f, --flood      Flood ping. Outputs packets as fast as they come back. Use
                   with caution!
  -6, --ipv6       Ping using IPv6.
  -t, --timeout=s  Specify a timeout, in seconds, before a ping packet is
                   considered 'lost'.
  -h, --help       Display this help and exit

Report bugs to lars [at] gnist org""" % os.path.basename(sys.argv[0])


if __name__ == '__main__':
    """Main loop
    """

    # version control
    version = string.split(string.split(sys.version)[0][:3], ".")
    if map(int, version) < [2, 3]:
        _error("You need Python ver 2.3 or higher to run!")

    try:
        # opts = arguments recognized,
        # args = arguments NOT recognized (leftovers)
        opts, args = getopt.getopt(sys.argv[1:-1], "hat:6c:fs:", \
                                   ["help", "alive", "timeout=", "ipv6", \
                                    "count=", "flood", "packetsize="])
    except getopt.GetoptError:
        # print help information and exit:
        _error("illegal option(s) -- " + str(sys.argv[1:]))

    # test whether any host given
    if len(sys.argv) >= 2:
        node = sys.argv[-1:][0]   # host to be pinged
        if node[0] == '-' or node == '-h' or node == '--help' :  
            _usage()
    else:
        _error("No arguments given")

    if args:
        _error("illegal option -- %s" % str(args))
        
    # default variables
    alive = 0; timeout = 1.0; ipv6 = 0; count = sys.maxint;
    flood = 0; size = ICMP_DATA_STR

    # run through arguments and set variables
    for o, a in opts:
        if o == "-h" or o == "--help":    # display help and exit
            _usage()
            sys.exit(0)
        if o == "-t" or o == "--timeout": # timeout before "lost"
            try:
                timeout = float(a)
            except:
                _error("invalid timout: '%s'" % str(a))
        if o == "-6" or o == "--ipv6":    # ping ipv6
            ipv6 = 1
        if o == "-c" or o == "--count":   # how many pings?
            try:
                count = int(a)
            except:
                _error("invalid count of packets to transmit: '%s'" % str(a))
        if o == "-f" or o == "--flood":   # no delay between ping send
            flood = 1
        if o == "-s" or o == "--packetsize":  # set the ping payload size
            try:
                size = int(a)
            except:
                _error("invalid packet size: '%s'" % str(a))
        # just send one packet and say "it's alive"
        if o == "-a" or o == "--alive":   
            alive = 1

    # here we send
    pingNode(alive=alive, timeout=timeout, ipv6=ipv6, number=count, \
             node=node, flood=flood, size=size)
    # if we made it this far, do a clean exit
    sys.exit(0)

### end
findbugs 过滤器 findbugs filter Findbugs使用手册
<FindBugsFilter>

	<!--  该类使用所有的bug检测器  -->
	<Match>
		<Class name="com.foobar.MyClass" />
	</Match>

	<!--  该类使用bugcode为HE的检测器  -->
	<Match class="com.foobar.BClass">
		<BugCode name="HE" />
	</Match>

	<!--  该类通过指定缩写名使用一些bug检测器  -->
	<Match>
		<Class name="com.foobar.MyClass" />
		<Bug code="DE,UrF,SIC" />
	</Match>

	<!--  所有类使用bugcode为HE的检测器  -->
	<Match>
		<BugCode name="HE" />
	</Match>

	<!--  所有类使用bugcode为DE,UrF,SIC的检测器  -->
	<Match>
		<Bug code="DE,UrF,SIC" />
	</Match>

	<!--  所有类通过指定检测器种类使用某些检测器  -->
	<Match>
		<Bug category="PERFORMANCE" />
	</Match>

	<!--  该类的指定方法使用bugcode为DC的检测器  -->
	<Match>

		<Class name="com.foobar.MyClass" />
		<Or>
			<Method name="frob" params="int,java.lang.String" returns="void" />
			<Method name="blat" params="" returns="boolean" />
		</Or>
		<Bug code="DC" />

	</Match>

	<!--  该类的AMethod和BMethod方法使用bugcode为DE,UrF,SIC的检测器  -->
	<Match>
		<Class name="com.foobar.MyClass" />
		<Or>
			<Method name="AMethod" />
			<Method name="BMethod" />
		</Or>
		<BugCode name="DE,UrF,SIC " />
	</Match> 

    <!--  该类的指定方法使用bug模式为OS_OPEN_STREAM的检测器 -->
	<Match>
		<Class name="com.foobar.MyClass" />
		<Method name="writeDataToFile" />
		<Bug pattern="OS_OPEN_STREAM" />
	</Match>

    <!-- 该类的某个方法使用优先级为2的bug模式DLS_DEAD_LOCAL_STORE 的检测器-->
	<Match>
		<Class name="com.foobar.MyClass" />
		<Method name="someMethod" />
		<Bug pattern="DLS_DEAD_LOCAL_STORE" />
		<Priority value="2" />
	</Match>

    <!-- 代码的指定部分使用指定bugcode或bug模式的检测器 -->
    <!-- 所有包的信息类使用bugcode为UUF的检测器-->
	<Match>
		<Class name="~.*\.Messages" />
		<Bug code="UUF" />
	</Match>

    <!-- 所有内部包使用bugcode为MS的检测器-->
	<Match>
		<Package name="~.*\.internal" />
		<Bug code="MS" />
	</Match>

    <!-- ui包层使用bug模式为SIC_INNER_SHOULD_BE_STATIC_ANON的检测器-->
	<Match>
		<Package name="~com\.foobar\.fooproject\.ui.*" />
		<Bug pattern="SIC_INNER_SHOULD_BE_STATIC_ANON" />
	</Match>

    <!-- 带指定标志的成员域或方法使用指定bugcode或bug模式的检测器-->
    <!-- 所有类中的void main(String[])方法使用bug模式为DM_EXIT的检测器-->
	<Match>
		<Method returns="void" name="main" params="java.lang.String[]" />
		<Bug pattern="DM_EXIT" />
	</Match>

    <!-- 所有类中的com.foobar.DebugInfo型的域使用bugcode为UuF的检测器-->
	<Match>
		<Field type="com.foobar.DebugInfo" />
		<Bug code="UuF" />
	</Match>

</FindBugsFilter>
python zipfile python zipfile
# -*- coding: UTF-8 -*-
'''
Created on 2011-6-9

@author: Administrator
'''

import os, zipfile
from os.path import join
import string

def zipfolder(foldername, filename, includeEmptyDIr=True):
    
    os.chdir(foldername)
    
    print foldername
    
    empty_dirs = []
    zip = zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(foldername):
        print root
        startpath = root.replace(foldername, "")
        print startpath
        empty_dirs.extend([dir for dir in dirs if os.listdir(join(root, dir)) == []])
        for name in files:
            tmp = join(startpath ,name)
            print tmp
            zip.write(join(startpath ,name))
        if includeEmptyDIr:
            for dir in empty_dirs:
                zif = zipfile.ZipInfo(join(startpath, dir) + os.sep)
                zip.writestr(zif, "")
        empty_dirs = []
    zip.close()

def zipDir():
    #sourceFold = 'D:\\www\\js'
    sourceFold = 'D:\\360Downloads\\pxto_com_cn\\site\\'
    targetFile = 'D:\\opt\\public\\technology\\test.zip'
    zipfolder(sourceFold, targetFile)
    
def pathtest():
    
    path = 'D:\\360Downloads\\pxto_com_cn\\site\\admin\\fuck'
    print path.replace("D:\\360Downloads\\pxto_com_cn\\site\\", "")
    print path
    
if __name__ == '__main__':

    zipDir()
expect获取某用户(id结果)并写入文件 expect http://bbs.chinaunix.net/thread-1639694-2-1.html
#!/usr/bin/expect

set host_ip "192.168.243.128"
set root_pwd "root"

set done 0
set donewitheof 0 

log_user 0

spawn ssh root@$host_ip "id mc"
while {!$done} {
    expect {
        eof {
            set done 1
            set donewitheof 1
        }
        -nocase -re "Permission denied*" {
            exit 1             
        }
        -nocase -re "password*" {
            send "$root_pwd\r"
        }
        -nocase -re "Are you sure you want to continue connecting*" {
            send "yes\r"
        }
        -nocase -re "\[\r\n\]+uid.+$" {
            set fd [open mc_groups "w+"]
            set result $expect_out(0,string)
            set result2 [string trim $result "\r\n"]
            puts $fd "$result2"
            flush $fd
            close $fd
        }
    }
}
shell 解析xml shell解析xml文件
#!/bin/bash

#@author wubingjie

#配置文件路径
XMLFILE=/home/wubingjie/dist.xml
XML_ROW=module
ATTR_PATH=path
SUB_ATTR_HOST=host
SUB_ATTR_RSYNC=rsync_module

#开关
FLAG=0

#自定义错误代码
ERR=65

[ -f ${XMLFILE} ] || exit ${ERR}
[ -z $1 ] && exit ${ERR}

#判断是否xml文件
file ${XMLFILE}|grep -qiE 'XML'|| exit ${ERR}

#分析文件
cat ${XMLFILE}|\

#换行
sed 's/>/>\n/g' 2>/dev/null|\

#去掉首尾空格
sed 's/\s*\(.*\)\s*$/\1/g'|\

#去掉"="左右两边的空白字符
sed 's/\s*\(=\)\s*/\1/g' 2>/dev/null|\

#去掉空白行
sed '/^\(\s\)*$/d' 2>/dev/null|\

while read line
do
 #节点开始
 if echo ${line}|grep -qE "^<$XML_ROW" \
 && echo ${line}|grep -qE "\b${ATTR_PATH}=\"$1\""; then
  FLAG=1
  continue
 fi

 #节点结束
 if echo ${line}|grep -qE "</${XML_ROW}>"; then
  FLAG=0 
 fi

 #子节点
 if [ ${FLAG} -eq 1 ] ; then
  #双引号和双引号两种情况
  tmp=`echo ${line}|sed "s/^\(.*\)\b${SUB_ATTR_HOST}=\"\([^\"]*\)\".*$/\2/" 2>/dev/null|\
  sed "s/^\(.*\)\b${SUB_ATTR_HOST}='\([^']*\)'.*$/\2/" 2>/dev/null`
  #提取IP
  echo ${tmp}|tr -d '[:space:]'|grep -qE '^[0-9]{1,3}(\.[0-9]{1,3}){3}' && echo ${tmp}  
 fi
done

exit $?
python 可编辑表格 python, wxpython python,wxpython学习2
import wx
from wx.lib import masked 
import re
import os
import sys

import  wx.lib.mixins.listctrl  as  listmix
class TestListCtrl(wx.ListCtrl, 
                   listmix.TextEditMixin):

    def __init__(self, parent, ID, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0):
        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
        
        listmix.TextEditMixin.__init__(self)
#        font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
#        font.SetPointSize(18)
#        self.SetFont(font)
		
	def OpenEditor(self, col, row):
        if col>1:
            listmix.TextEditMixin.OpenEditor(self,col, row)
            
    def CloseEditor(self, evt=None):
        listmix.TextEditMixin.CloseEditor(self, evt)
        item = self.GetItem(self.curRow,col=1)
        oldname = item.GetText()
        item = self.GetItem(self.curRow,col=2)
        newname = item.GetText()
        if oldname != newname:
            self.SetItemBackgroundColour(self.curRow,"pink")
        else:
            self.SetItemBackgroundColour(self.curRow,"white")

class FileRenameDialog(wx.Dialog):
    def __init__(self):
        wx.Dialog.__init__(self, None, -1, "Rename OS File Name ",size=(800, 600),
                           style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.MINIMIZE_BOX)

        sizer = wx.GridBagSizer(hgap=5, vgap=5)
        
        #ROW 0
        lb = wx.StaticText(self, -1, "目录:")
        sizer.Add(lb, pos=(0,0),flag=wx.LEFT|wx.TOP,border=20)
        
        self.text_path = wx.TextCtrl(self,-1, "")
        sizer.Add(self.text_path, pos=(0,1), flag=wx.EXPAND|wx.TOP,border=20)
        
        bt_path = wx.Button(self,-1,"浏览...",name="bt_path")
        sizer.Add(bt_path, pos=(0,2),flag=wx.TOP|wx.RIGHT,border=20)
        
        #ROW 1
        lb = wx.StaticText(self, -1, "模式:")
        sizer.Add(lb, pos=(1,0),flag=wx.LEFT,border=20)
        
        self.cb = wx.ComboBox(self, -1, "default value",style = wx.CB_READONLY)
        self.cb.Append("正则表达式替换(eg. 数字前后加括号 123->(123) )", "ClientData")
        self.cb.Append("匹配分组(group(1))填充(eg. 1->001,12->012)", "ClientData")
        #self.cb.SetSelection(0)
        sizer.Add(self.cb, pos=(1,1), flag=wx.EXPAND,border=20)
		
		#ROW 2
        lb = wx.StaticText(self, -1, "查找:")
        sizer.Add(lb, pos=(2,0),flag=wx.LEFT,border=20)
        
        self.text_find = wx.TextCtrl(self,-1, "")
        sizer.Add(self.text_find, pos=(2,1), flag=wx.EXPAND,border=20)
        
        #ROW 3
        lb = wx.StaticText(self, -1, "替换:")
        sizer.Add(lb, pos=(3,0),flag=wx.LEFT,border=20)
        
        self.text_replace = wx.TextCtrl(self,-1, "")
        sizer.Add(self.text_replace, pos=(3,1), flag=wx.EXPAND,border=20)
        
        #ROW 4           
        groupbox = wx.StaticBox(self, -1, "填充选项:",name="groupbox_sbox")
        groupsizer = wx.StaticBoxSizer(groupbox, wx.HORIZONTAL)
      
        self.chk_left = wx.RadioButton(self, -1, "左填充",name="groupbox_chkleft")
        groupsizer.Add(self.chk_left, 0,flag=wx.LEFT|wx.ALIGN_CENTER,border=0)
        
        
        self.chk_right = wx.RadioButton(self, -1, "右填充",name="groupbox_chkleft")
        groupsizer.Add(self.chk_right, 0,flag=wx.LEFT|wx.ALIGN_CENTER,border=10)
     
        lb = wx.StaticText(self, -1, "字符:",name="groupbox_lb")
        groupsizer.Add(lb, 0,flag=wx.LEFT|wx.ALIGN_CENTER,border=30)
        self.text_padchar = masked.TextCtrl(
                                self, -1, value='0', mask='*', \
								includeChars = ' ', excludeChars = '',\
                                formatcodes='F', emptyInvalid=False, \
								validRequired=True,name="groupbox_masktext")
								
        groupsizer.Add(self.text_padchar, 0,flag=wx.LEFT|wx.ALIGN_CENTER,border=0)
               
        lb = wx.StaticText(self, -1, "长度:",name="groupbox_lb")
        groupsizer.Add(lb, 0,flag=wx.LEFT|wx.ALIGN_CENTER,border=20)
        self.text_padlen = masked.NumCtrl(self, value=3, integerWidth=2, \
			allowNegative=False,name="groupbox_numtext")
        groupsizer.Add(self.text_padlen, 0,flag=wx.LEFT|wx.ALIGN_CENTER,border=0)
        
        sizer.Add(groupsizer, pos=(4,0),span=(1,2), flag=wx.EXPAND|wx.LEFT,border=20)

        #ROW 5           
        groupbox = wx.StaticBox(self, -1, "预览:",name="groupbox2_sbox")
        groupsizer = wx.StaticBoxSizer(groupbox, wx.VERTICAL)


        t = wx.StaticText(self, -1, "点击<替换预览>进行预览,\
			预览后点击<进行替换>进行操作系统文件重命名")
        groupsizer.Add(t, 0, wx.TOP|wx.LEFT, 0)
        
        #self.list = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_HRULES)
        self.list = TestListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_HRULES)
        self.list.InsertColumn(0, "序号",format=wx.LIST_FORMAT_LEFT, width=40)
        self.list.InsertColumn(1, "原文件名",format=wx.LIST_FORMAT_LEFT, width=280)
        self.list.InsertColumn(2, "替换后文件名",format=wx.LIST_FORMAT_LEFT, width=280)
        groupsizer.Add(self.list, 1, wx.EXPAND|wx.TOP, 10)
		
        sizer.Add(groupsizer, pos=(5,0),span=(2,2), \
			flag=wx.EXPAND|wx.LEFT|wx.TOP|wx.BOTTOM,border=20)

  
        bt_preview = wx.Button(self,-1,"替换预览",name="bt_preview")
        sizer.Add(bt_preview, pos=(5,2),flag=wx.ALIGN_BOTTOM|wx.TOP|wx.RIGHT,border=20)
        
        #ROW 6           
        #grid span part
        
        bt_replace = wx.Button(self,-1,"进行替换",name="bt_ok")
        sizer.Add(bt_replace, pos=(6,2),flag=wx.ALIGN_CENTER|wx.TOP|wx.RIGHT|wx.BOTTOM,border=20)


        sizer.AddGrowableCol(1)
        sizer.AddGrowableRow(5)
        
        
        
        self.SetSizer(sizer)
       

        self.EnablePadding(False)
        
        
        #Event Mapping
        self.Bind(wx.EVT_COMBOBOX, self.EvtComboBox, self.cb)
        self.Bind(wx.EVT_BUTTON, self.OnButton_SelPath, bt_path)
        self.Bind(wx.EVT_TEXT, self.OnText_Change, self.text_path)
        #self.text_path.Bind(wx.EVT_KILL_FOCUS, self.OnText_Change)
        self.Bind(wx.EVT_BUTTON, self.OnButton_Preview, bt_preview)
        self.Bind(wx.EVT_BUTTON, self.OnButton_Replace, bt_replace)
        
 
        self.Center()
       

    def EnablePadding(self,bEnable = False):
        lists = self.GetChildren()
        for ctrl in lists:
            if re.match('groupbox_.*$',ctrl.Name) is not None :
                ctrl.Enable(bEnable)
            
    
    def EvtComboBox(self, evt):
        if evt.GetSelection()==0 :
            self.EnablePadding(False)
            self.text_replace.Enable(True)
            self.text_find.Value = r"(\d+)";
            self.text_replace.Value = r"(\1)";
            
        elif evt.GetSelection()==1 :
            self.EnablePadding(True)
            self.text_replace.Enable(False)
            self.text_find.Value = r"(\d+)";
            self.text_replace.Value = "";  
            self.chk_left.SetValue(True)
            self.text_padchar.Value="0"
            self.text_padlen.Value=" 3"     
   
            
    def OnButton_SelPath(self, evt):
        # In this case we include a "New directory" button. 
        dlg = wx.DirDialog(self, "请选择文件所在目录:",
                          style=wx.DD_DEFAULT_STYLE
                           | wx.DD_DIR_MUST_EXIST
                           | wx.DD_CHANGE_DIR
                           )
        if dlg.ShowModal() == wx.ID_OK:
            self.text_path.Value = dlg.GetPath()

        dlg.Destroy()
    
        
    def OnText_Change(self, evt):
        self.LoadFiles(evt.GetString())

     
    def OnButton_Preview(self, evt):
        for i in range(self.list.GetItemCount()):
            item = self.list.GetItem(i,col=1)
            oldname = item.GetText()
            
            newname = self.DoRegExSub(oldname)
            
            self.list.SetStringItem(i, 2, newname)
            if oldname != newname:
                self.list.SetItemBackgroundColour(i,"pink")
            else:
                self.list.SetItemBackgroundColour(i,"white")
				
    def OnButton_Replace(self, evt):
        if wx.MessageBox('是否根据预览内容进行文件重命名操行?      ','请确认',
                         wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) == wx.YES:
            path = self.text_path.Value
            count=0
            try:
                for i in range(self.list.GetItemCount()):
                    item = self.list.GetItem(i,col=1)
                    oldfullname = os.path.join(path,item.GetText())
                    item = self.list.GetItem(i,col=2)
                    newfullname = os.path.join(path,item.GetText())
                    if oldfullname != newfullname:
                        os.rename(oldfullname, newfullname)
                        count = count + 1
            except:
                wx.MessageBox('文件重命名遇到错误,但已重命名 ' \
					+ str(count) + ' 个','错误',style=wx.ICON_ERROR|wx.OK)
                
            else:
                wx.MessageBox('文件重命名成功完成,已重命名 ' \
					+ str(count) + ' 个','提示',style=wx.ICON_INFORMATION|wx.OK)
                self.LoadFiles(path)


        
    def LoadFiles(self,path):
        if os.path.exists(path):
            self.list.DeleteAllItems()
            i=0
            for name in os.listdir(path):
                fullname = os.path.join(path,name)
                if os.path.isfile(fullname):
                    index = self.list.InsertStringItem(i, str(i+1))
                    self.list.SetStringItem(index, 1, name)
                    i = i + 1
      
      
      
    def func_pad(self,m): 
        len = int(self.text_padlen.Value)
        ch = self.text_padchar.Value
        if self.chk_left.Value:
            return m.group(1).rjust(len,ch)
        else: 
            return m.group(1).ljust(len,ch)
        
    def DoRegExSub(self,s):
        
        to = self.text_replace.Value
        new = ''  
         
        try:
            r = re.compile(self.text_find.Value)

            if self.cb.GetSelection()==0 :
                new = r.sub(to,s,1)
            elif self.cb.GetSelection()==1 :
                new = r.sub(self.func_pad,s,1)
        except:
            new= '@err:' + str(sys.exc_info()[0]) + str(sys.exc_info()[1])
        
        return new
        
        
           
       

if __name__ == '__main__':
    app = wx.PySimpleApp()
    
    filenamedlg = FileRenameDialog()
    filenamedlg.Show()
    
    app.MainLoop()
Global site tag (gtag.js) - Google Analytics