【python】python实例集<一>


#打开一个记事本
import os
os.startfile('notepad.exe')
#当前文件的根目录
import os
print os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)

 #获取本机IP

import socket
hostname = socket.gethostname()
print  hostname
IPinfo = socket.gethostbyname_ex(hostname)
print IPinfo
LocalIP = IPinfo[2]
print LocalIP 
#定时器执行一个命令
import os
import time
def print_ts(message):
    print "[%s] %s"%(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), message)##time.strftime把时间格式化
def run(interval, command):
    print_ts("-"*100)
    print_ts("Command %s"%command)
    print_ts("Starting every %s seconds."%interval)
    print_ts("-"*100)
    while True:
        try:
            # sleep for the remaining seconds of interval,http://www.sharejs.com
            print_ts("Sleeping until %s..."%((time.ctime(time.time()+interval))))#time.ctime把时间戳变为年月日形式
            time.sleep(interval)
            print_ts("Starting command.")

            # execute the command
            status = os.system(command)
            print_ts("-"*100)
            print_ts("Command status = %s."%status)
        except Exception, e:
            print e
if __name__=="__main__":
    interval = 600
    command = r"ipconfig"
    run(interval, command)

#正则表达式,读取tomcat的日志并打印日期
import re
regx = "\d\d\d\d-\d\d-\d+"
f = open("c:\stdout.log","r")
i = 0
for str in f.readlines():
if re.search(regx,str):
     Response.write(str+"<br>")
      if i>10:break#由于是测试,只分析十行
      i=i+1
f.close()
#输出当前windows下的所有活动窗口名称
from win32gui import *
titles = set()
def foo(hwnd,mouse):
  if IsWindow(hwnd) and IsWindowEnabled(hwnd) and IsWindowVisible(hwnd):
    titles.add(GetWindowText(hwnd))
EnumWindows(foo, 0)
lt = [t for t in titles if t]
lt.sort()
for t in lt:
  print t

#定时监听ip和端口

#-*- coding: gbk -*-
import socket,time
while 1:
    file_obj = open('ip.txt')
    for line in file_obj:
        try:
            sc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            ip = line.split()[0]
            port = int(line.split()[1])
            print ip,port
            #设置超时时间(0.0)
            sc.settimeout(2)
            sc.connect((ip,port))
            timenow=time.localtime()
            datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)
            logstr="%s:%s 连接成功->%s \n" %(ip,port,datenow)
            print logstr
            sc.close()
        except:
            file = open("log.txt", "a")
            timenow=time.localtime()
            datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)
            logstr="%s:%s 连接失败->%s \n" %(ip,port,datenow)
            print logstr
            file.write(logstr)
            file.close()
    print "sleep 10....."
    time.sleep(10)

  

你可能感兴趣的:(【python】python实例集<一>)