Results tagged “python” from WHO IS 2HEI?

require : python2.6 pytz

#!/usr/bin/env python
# -*- coding: gbk -*-
from datetime import datetime, timedelta
from time import gmtime, strftime
from pytz import timezone
import pytz, time,os

#def convert_datetime(unix_timestamp=1143408000, tz=1, long_fmt=1):
def convert_datetime(dt='2007-01-01 00:00:00', tz='', dest_fmt='', time_stamp=0):
    fmt      = '%Y-%m-%d %H:%M:%S'
    if time_stamp == 0:
        dt_stamp = time.mktime(time.strptime(dt, fmt))
    else:
        dt_stamp = float(dt)
    utc      = pytz.utc
    utc_dt   = datetime.utcfromtimestamp(dt_stamp).replace(tzinfo=utc)  
    dest_tz  = timezone(tz)
    dest_dt  = dest_tz.normalize(utc_dt.astimezone(dest_tz))  
    return dest_dt.strftime(dest_fmt)

#define all citys here
citys = {'Asia/Shanghai':'Asia/Shanghai 上 海',
        'America/Los_Angeles':'America/Los_Angeles 旧金山',
        'Etc/GMT':'Etc/GMT 格林威治标准时间',
        'US/Pacific':'US/Pacific PT 太平洋时间',
        'UTC':'UTC 世界标准时间',
        #'Etc/GMT+8':'Etc/GMT+8',
       }
 
if __name__ == '__main__':
    while True:
        os.system('cls')
        print '--------------时间对照--------------'
        for k,v in citys.items():
            print convert_datetime(dt=strftime("%Y-%m-%d %H:%M:%S", time.localtime()), tz=k,dest_fmt='%Y-%m-%d %H:%M:%S'),'\t['+v+']'
        print '------------------------------------'
        time.sleep(1)

       
run.bat
set path=D:\python26\;%path%
D:
cd D:\Profiles\2hei.net\eclipse-project\py\myapp\src\time_format
python world_time.py

running like this:

world_time_zone.png













 

| | Comments (0) | TrackBacks (0)

python版本:2.6

案例一: test.xml
<?xml version="1.0" encoding="utf8"?>
调用:
xmldoc = minidom.parse(test.xml)
报错:
Traceback (most recent call last):
  File "D:\project\src\myapp\src\xml\testdomxml.py", line 14, in <module>
    xmldoc = minidom.parse(response)
  File "D:\Python\lib\xml\dom\minidom.py", line 1918, in parse
    return expatbuilder.parse(file)
  File "D:\Python\lib\xml\dom\expatbuilder.py", line 928, in parse
    result = builder.parseFile(file)
  File "D:\Python\lib\xml\dom\expatbuilder.py", line 207, in parseFile
    parser.Parse(buffer, 0)
xml.parsers.expat.ExpatError: unknown encoding: line 1, column 30


修改后:test2.xml
<?xml version="1.0" encoding="utf-8"?>
再次调用
xmldoc = minidom.parse(test2.xml)
没有问题了。 囧一个!

详细可见python bug 列表: http://bugs.python.org/msg63471


案例二:
xmldoc = minidom.parse(urllib.urlopen('http://rss.sina.com.cn/news/marquee/ddt.xml'))
正常调用

xmldoc = minidom.parse(urllib.urlopen('http://news.163.com/special/00011K6L/rss_newstop.xml''))
报错:
  File "D:\Python\lib\xml\dom\expatbuilder.py", line 207, in parseFile
    parser.Parse(buffer, 0)
xml.parsers.expat.ExpatError: unknown encoding: line 1, column 30

观察sina和163的两个rss源文件看,并未发现特别的异常,不过将163的保存为文件rssnew163.xml,在其头部添加
<?xml version="1.0" encoding="utf-8"?>
然后再调用
xmldoc = minidom.parse("rssnew163.xml")
问题解决,看来还是字符编码的问题了。
对于使用urllib实时更新rss的就需要预先处理一下了,先保存rss文件,然后添加上述行,或者将xml文件转换成utf-8编码即可。

| | Comments (3) | TrackBacks (0)
linux用shell实现menu比较简单,今天用python实现了一个,因为python没有switch语法,所以使用了dict来替代,另外调用了linux的clear来清屏,本例只是说明一下简单的实现方法,菜单的命令或者语句可以自由发挥 呵呵。

截个图先:
2009-11-17-linux-python-menu.png

















具体代码如下:
#!/usr/bin/evn python
# -*- coding: utf-8 -*-
#Author: 2hei#2hei.net
#Date: 2009-11-17 18:24

import os,sys

running = True
menu = """
             menu
------------------------------
    1:   Disk info
    2:   Mem info
    3:   Network info
    4:   Sys load info
    5:   Process info
    h:   Help
    q:   Quit
------------------------------
"""

menu_dict={
      "h": "echo help ^_^",
      "1": "df -h",
      "2": "free -m",
      "3": "netstat -lnt",
      "4": "uptime",
      "5": "ps x"
      }

def commands(args):
    cmd = menu_dict.get(args)
    return cmd

if __name__ == "__main__":
    os.system('clear')
    print menu   
    while running:
        cmd = raw_input("Input your commond :\n")
        if cmd != 'q':
            os.system('clear')
            try:
                print menu
                if commands(cmd) != None:
                    fo = os.popen(commands(cmd))
                    print fo.read()
                else:
                    print "Input is Wrong!\n"
            except Exception,e:
                print menu
                print e            
        else:
            print 'we will exit the menu\n'
            sys.exit()


| | Comments (0) | TrackBacks (0)
python 访问带有web认证的页面,经测试方法一可用!

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#方法一
#--------------------------------------------------------------
def request_auth_http(url, User = None, Pass = None):
    import urllib2
    # this creates a password manager
    passman = urllib2.HTTPPasswordMgrWithDefaultRealm()    
    passman.add_password(None, url, User, Pass)
    # create the AuthHandler
    authhandler = urllib2.HTTPBasicAuthHandler(passman)    
    opener = urllib2.build_opener(authhandler)    
    urllib2.install_opener(opener)
    pagehandle = urllib2.urlopen(url)
    data = pagehandle.read()
    pagehandle.close()
    return data

#方法二
#--------------------------------------------------------------
    #auth = "Basic %s" % base64.encodestring("%s:%s" % (User, Pass))[:-1]
    #request.add_header("User-Agent", "Python-2.5")
    #request.add_header("Authorization",auth)
    #opener = urllib2.build_opener()    
    #data = opener.open(request).read()
    #print data
    #htmlFile = urllib2.urlopen(request)
    #htmlData = htmlFile.read()
    #htmlFile.close()
    #return htmlData

#--------------------------------------------------------------
def main():
    url = "https://2hei.net/login"
    User = "user"
    Pass = "passwd"
    print request_auth_http(url,User,Pass)

#--------------------------------------------------------------
if __name__ == "__main__":
    main()

实际的结果是,方法一正解,方法二页面返回401错误。


| | Comments (0) | TrackBacks (0)
python 使用BeautifulSoup(美汤)来抓取天气预报,简单的例子,只当练手

#!/usr/bin/env python
# -*- coding: gb2312 -*-

#get weather info from internet
#http://weather.china.com.cn/city/54511_full.html

import urllib,re,unicodedata,string,sys,re
from BeautifulSoup import *

if __name__=="__main__":
    response = urllib.urlopen("http://weather.china.com.cn/city/54511_full.html")
    result = response.read()
    soup = BeautifulSoup(''.join(result))
    weather = soup.findAll('td')
    list = []
    tmplist = []
    for i in xrange(0,len(weather)):
        tmpstr = weather[i].string
        if tmpstr not in ['&nbsp;',None,u'地方气象网站','合作伙伴:中国气象局中央气象台',u'天气预报']:
            list.append(tmpstr)
    for j in xrange(0,4):
        print list[j]


result is:
北京
气温:29 ℃~17 ℃
风向:微风
风力:小于3 级
| | Comments (0) | TrackBacks (0)
BeautifulSoup 在处理rss页面时发现了如下问题,在rss页面中如果包含<link>标签,BeautifulSoup 处理的不好,具体如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib,re,unicodedata,string,sys,re
from BeautifulSoup import *

if __name__=="__main__":
    response = urllib.urlopen("http://news.163.com/special/00011K6L/rss_newstop.xml")
    result = response.read()
    soup = BeautifulSoup(''.join(result))
    print soup.originalEncoding   
    print soup.prettify()
    news = soup.findAll('link')
    print news

============
gbk
<?xml version='1.0' encoding='utf-8'?>
<?xml version='1.0' encoding='utf-8'?>
<rss version="2.0">
 <channel>
  <title>
   网易头条新闻
  </title>
  <link />
  http://news.163.com/
  <description>
   头条新闻
  </description>
  <item id="1">
   <title>
    <![CDATA[人民日报:人民精神文化生活"前所未有的丰富"]]>
   </title>
   <link />
   http://news.163.com/09/0914/13/5J6444CA0001124J.html
   <description>
    <![CDATA[人民网9月14日报道 新中国成立60年来,我国新闻出版事业走过了不平凡的历程。从中人们能深切感受到它对振奋精神、凝聚力量、促进改革发展稳定的巨大作用,也会切身体会到其与时代同行、与人民同心的历史性进步。 这种进步,可以从两个方面来考量。一方面是这些年来新闻出版业“前所未有的创新”。从全面推动宣传思想工作“  ]]>
    ......
   </description>
   <pubdate>
    2009-09-14 13:19:09
   </pubdate>
  </item>
...
...

[<link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />, <link />]

结果可以看到没有取到link标签的内容,应该是BeautifulSoup在自作聪明的补全标签时出现了问题。

| | Comments (1) | TrackBacks (0)

在使用python写的cgi是遇到如下问题
Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 20] Not a directory: '/dev/null/.python-eggs' The Python egg cache directory is currently set to: /dev/null/.python-eggs Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory.

分析其主要原因是启动http服务的用户没有主目录,所以系统默认给分配了/dev/null这个目录,所以当要在/dev/null/中解开egg文件时,会有错误
解决办法为设定PYTHON_EGG_CACHE变量即可,具体如下:

import os
os.environ['PYTHON_EGG_CACHE'] = '/tmp/'

 

| | Comments (0) | TrackBacks (0)
      小三(E63)入手已经几个月了,现在越发的感觉用着顺手,从dospy上看到了很多有价值的东西,也学到了不少关于symbian的知识。
     
       小三的功能强大,忍耐力超强、任劳任怨、毫无怨言,除了每早班车上一路陪伴的飞鱼秀外,还给装上了一堆经典老游戏(超级玛丽、泡泡龙、need for speed 街霸II、三国志、sky force 当然还有gameloft经典游戏asphalt4),装上了工作中经常用到的putty,还有可替代数据线的超级工具symsmb4,最近把我挚爱的大蛇(python)给捣鼓进去了,而且写了一个最经典的hello world!
      看了python for S60自带的贪吃蛇的代码,居然如此精炼,着实也让我兴奋了一番,有时间再研究下py2sis,咱也赶赶时髦,也整点手机应用啥的,最起码写出个win95来吧,哈哈!
win95-1.jpg

| | Comments (0) | TrackBacks (0)
pyhon中很简单的模块调用

#!/usr/bin/python
# Filename: abc.py

def mymo():
    print 'hello world!'



#!/usr/bin/python
# Filename: ehcoabc.py

import abc

abc.mymo()

执行结果如下:
    AttributeError: 'module' object has no attribute 'mymo'

原因是abc在python中比较特殊,跟已有的module模块冲突,换一下名字就可以了。

| | Comments (0) | TrackBacks (0)
python连接mysql中我遇到了这样的问题
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "build/bdist.linux-i686/egg/MySQLdb/__init__.py", line 81, in Connect
  File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 188, in __init__
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
mysql启动是参数设定的比较多,我的mysql启动脚本:
/home/2hei/mysql/bin/mysqld --defaults-file=/home/2hei/mysql/etc/my.cnf --basedir=/home/2hei/mysql --datadir=/home/2hei/mysql/data --log-error=/home/2hei/mysql/data/2hei.net.err --pid-file=/home/2hei/mysql/data/mysqld.pid --socket=/tmp/mysql.sock --port=13306

#!/usr/bin/env python
# -*-coding:UTF-8-*
import MySQLdb
conn = MySQLdb.Connection(host='localhost',port=13306,user='2hei',passwd='123456',db='pytest')
cur = conn.cursor()
cur.execute('select * from test')
row=cur.fetchall()
print row


一直提示我mysql.scok出错。看了MySQLdb的源码后发现可以设定的参数还有很多
------------------------------------
class Connection(_mysql.connection):

    """MySQL Database Connection Object"""

    default_cursor = cursors.Cursor
   
    def __init__(self, *args, **kwargs):
        """

        Create a connection to the database. It is strongly recommended
        that you only use keyword parameters. Consult the MySQL C API
        documentation for more information.

        host
          string, host to connect
         
        user
          string, user to connect as

        passwd
          string, password to use

        db
          string, database to use

        port
          integer, TCP/IP port to connect to

        unix_socket
          string, location of unix_socket to use

        conv
          conversion dictionary, see MySQLdb.converters

        connect_timeout
          number of seconds to wait before the connection attempt
          fails.

        compress
          if set, compression is enabled

        named_pipe
          if set, a named pipe is used to connect (Windows only)

        init_command
          command which is run once the connection is created

        read_default_file
          file from which default client values are read

        read_default_group
          configuration group to use from the default file

        cursorclass
          class object, used to create cursors (keyword only)

        use_unicode
          If True, text-like columns are returned as unicode objects
          using the connection's character set.  Otherwise, text-like
          columns are returned as strings.  columns are returned as
          normal strings. Unicode objects will always be encoded to
          the connection's character set regardless of this setting.

        charset
          If supplied, the connection character set will be changed
          to this character set (MySQL-4.1 and newer). This implies
          use_unicode=True.

        sql_mode
          If supplied, the session SQL mode will be changed to this
          setting (MySQL-4.1 and newer). For more details and legal
          values, see the MySQL documentation.
         
        client_flag
          integer, flags to use or 0
          (see MySQL docs or constants/CLIENTS.py)

        ssl
          dictionary or mapping, contains SSL connection parameters;
          see the MySQL documentation for more details
          (mysql_ssl_set()).  If this is set, and the client does not
          support SSL, NotSupportedError will be raised.

        local_infile
          integer, non-zero enables LOAD LOCAL INFILE; zero disables
    --------------------------

于是修改源码为:
conn = MySQLdb.Connection(host='localhost',port=13306,user='2hei',passwd='123456',db='pytest',unix_socket='/tmp/mysql.sock')
这样执行后可以得到正确的结果:
$python link_mysql.py
((1L, 'ronaldo', 23L), (2L, 'figo', 30L))

问题得以解决!




| | Comments (0) | TrackBacks (0)
windows下的文件时间戳有三个属性,创建时间、修改时间、访问时间*nix下方便的多了,可以使用touch来进行修改,windows下也可以使用专门的工具来进行修改(别跟我说你是通过修改操作系统时间后再创建文件哟!)
本文使用python2.6来进行处理,代码很简单,美中不足的是python提供的模块中并没有可以修改文件创建时间的,而修改时间和访问时间均可以任意修改,代码具体如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys,time
from stat import *
filename='D:\\2hei.net\\test.txt'
#指定期望修改后的时间
TimeForChange = '2007-01-10 07:51:21'
#转换时间格式为long型
ConverTime = time.mktime(time.strptime( TimeForChange,'%Y-%m-%d %H:%M:%S') )
print TimeForChange+' 转换后:'+str(ConverTime)

print '-------------修改前----------------'
#创建时间
print '创建时间  '+time.ctime(os.path.getctime(filename))
#最后修改时间
print '修改时间  '+time.ctime(os.path.getmtime(filename))
#访问时间
print '访问时间  '+time.ctime(os.path.getatime(filename))

#修改文件时间戳
times=(ConverTime,ConverTime)
#进行修改
os.utime(filename, times)

print '-------------修改后----------------'
#创建时间
print '创建时间  '+time.ctime(os.path.getctime(filename))
#最后修改时间
print '修改时间  '+time.ctime(os.path.getmtime(filename))
#访问时间
print '访问时间  '+time.ctime(os.path.getatime(filename))

首先在本地创建一个test.txt的文件(文件夹类似),先右键点击查看属性:
2008-12-07_184152.png






























可以看到文件的三个基本属性,时间都是2008年12月7日,
程序运行的输出结果:
2007-01-10 07:51:21 转换后:1168386681.0
-------------修改前----------------
创建时间  Sun Dec 07 18:16:56 2008
修改时间  Sun Dec 07 18:41:38 2008
访问时间  Sun Dec 07 00:00:00 2008
-------------修改后----------------
创建时间  Sun Dec 07 18:16:56 2008
修改时间  Wed Jan 10 07:51:22 2007
访问时间  Wed Jan 10 00:00:00 2007

在右键点击查看文件属性,可以看到已经变成如下图:
2008-12-07_184427.png





































可以看到文件的修改时间已经变成了2007年的1月10日,时间属性修改成功。

| | Comments (0) | TrackBacks (0)
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#ip转化为long型格式
def iptolong(ipaddr):
    data = 0L
    ip = ipaddr.split('.')
    for i in range(0,len(ip)):
        if 0 <= long(ip[i]) < 256:
            data = data+long(ip[i])*(256**(3-i))
        else:
            data = 0L
            break
    return data

#long型转化成ip格式
def longtoip(iplong):
    i_4 = iplong % 256
    i_3 = (iplong - i_4)/256 % 256
    i_2 = (iplong - i_3*256 - i_4)/256**2 % 256
    i_1 = (iplong - i_2*256*256 - i_3*256 - i_4)/256**3 % 256
    ip = str(i_1)+'.'+str(i_2)+'.'+str(i_3)+'.'+str(i_4)
    return ip



| | Comments (0) | TrackBacks (0)

python socket.errorTab's error List

{
10048: 'The network address is in use.',
10054: 'The connection has been reset.',
10022: 'An invalid operation was attempted.',
10058: 'The network has been shut down.',
10060: 'The operation timed out.',
10061: 'Connection refused.',
10063: 'The name is too long.',
10064: 'The host is down.',
10065: 'The host is unreachable.',
10035: 'The socket operation would block',
10004: 'The operation was interrupted.',
10036: 'A blocking operation is already in progress.',
10009: 'A bad file handle was passed.',
10013: 'Permission denied.',
10014: 'A fault occurred on the network??'
}
| | Comments (0) | TrackBacks (0)

2008年8月。各大搜索引擎如google,msn,yahoo等统计计算出的结果,显示编程语言的关注程度,可见Python排名上升很快。

详细请见来源 tiobe

Position
Aug 2008
Position
Aug 2007
Delta in PositionProgramming
Language
Ratings
Aug 2008
Delta
Aug 2007
Status
1 1 Java 21.571% -0.20%   A
2 2 C 16.178% +0.48%   A
3 3 (Visual) Basic 10.857% +0.21%   A
4 4 C++ 10.057% -0.05%   A
5 5 PHP 9.349% -0.35%   A
6 8 Python 4.975% +2.23%   A
7 6 Perl 4.694% -0.63%   A
8 7 C# 3.697% -0.29%   A
9 10 Ruby 2.920% +1.01%   A
10 9 JavaScript 2.892% +0.32%   A
11 14 Delphi 2.732% +1.51%   A
12 13 D 1.357% +0.11%   A
13 11 PL/SQL 0.679% -1.15%   A-
14 12 SAS 0.549% -0.84%   B
15 - PowerShell 0.440% +0.44%   B
16 24 Pascal 0.416% +0.00%   B
17 18 Lisp/Scheme 0.379% -0.21%   B
18 15 Lua 0.373% -0.27%   B
19 16 COBOL 0.358% -0.24%   B
20 23 ActionScript 0.355% -0.07%   B


Long term trends

The long term trends for the top 10 programming languages can be found in the line diagram below.

| | Comments (0) | TrackBacks (0)

因为原来用JAVA写得访问URL的程序结果不是非常准确。索性决定用python重写一个,用来检测网页访问速度,
其中用到了httplib、urllib和time等模块。

初学PYTHON,发现当请求访问带有SSL的URL如:“https://google.com 时,httplib.HTTP就显得力不从心,
后来发现httplib已经有HTTPSConnection方法可以解决这个问题。
可惜HTTPSConnection没有HTTP的getreply()方法,所以无法得到页面请求状态码,不知是否有达人了解。

因为在Windows下开发的(Eclipse+pydev),移植到Linux下居然报错,系统提示段错误( python segmentation faults   )。查了一下,有说系统CORE DOWN可能会有这种结果,吼吼,python不会如此厉害吧。

Google了半天,终于找到原因,居然是Python的版本所致,本机python的版本是2.5.2,而Linux是2.3.4,呵呵,赶紧升级到2.5,搞定!

| | Comments (0) | TrackBacks (0)

开始学习python,试着配置了一下开发环境

PS:系统Win,已经安装了python2.4以上、并且配置好环境变量,另外安装jdk 1.4以上版本、

eclipse+pydev

下载eclipse的最新版本3.4,

登陆http://www.fabioz.com/pydev/站点下载最新版本Release 1.3.18 ,我试过使用eclipse自带的plug更新没有成功,虽然我指定了可以更行的URL,并且可以找到pydev的模块,可惜出现了异常,所以只好手动下载zip文件。

可以到http://www.fabioz.com/pydev/zips/找到最新版本进行下载

解压到eclipse的plugin目录和features目录,然后配置eclipse的pydev插件,可以指定python.exe的安装目录,

eclipse提到了jython的插件,使用户能以Python语言的语法编写在Java虚拟机上运行的软件。它的特点有:与相似的Java程序相比,Jython极大的的减少了编程代码量。Jython同时拥有解释器和编译器,使其无需编译就可以测试程序代码。

配置好以后,就可以进行python的开发了,带有自动缩进和高亮提示及语法提示,eclipse的功能还真是强大!

 

| | Comments (0) | TrackBacks (0)

标签