月度归档: 2019 年 1 月

wxpython 从剪贴板读取文件,读取文字,读取图像

需求

前段时间有这样一个需求,要读取用户的剪贴板的内容,然后把剪贴板的信息复制到另一个地方。例如:

  • 当用户复制的是图片时,把图片复制到一个指定位置。
  • 当用户复制的是txt中的一段文字时,获得复制的文字内容。
  • 当用户复制的是一个文件时,获得复制的文件名和路径,然后复制到一个指定位置。

设计

1.通过wx自带的检查剪贴板功能。
wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_BITMAP)) 这样的方式,判断是不是图片。
文字和文件的方法类似,可以在下面的代码里看到。
2.通过wx.TheClipboard.GetData(file_obj)的方法获得剪贴板的内容
3.如果是图片,通过wx.BitmapDataObject()的GetBitmap()方法获得图片信息。再通过SaveFile(name=filename, type=wx.BITMAP_TYPE_BMP)方法保存图片
4.如果是文字。通过wx.TextDataObject()的GetText()方法获得文字内容。
5.如果是文件。通过wx.FileDataObject()的GetFilenames()获得复制的文件列表。然后可以通过shutil库的copy2方法复制文件到指定位置

wxpython窗体的部分代码

#!/usr/bin/env python
import wx
class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title="Paste Button Demo")
        self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.HSCROLL)
        self.count = 4  # gets incremented
        menu = wx.MenuBar()
        edit = wx.Menu()
        paste = edit.Append(wx.ID_PASTE, "&Paste", "Paste from the clipboard")
        menu.Append(edit, "&Edit")
        self.SetMenuBar(menu)
        self.toolbar = self.CreateToolBar()
        bmp = wx.ArtProvider.GetBitmap(wx.ART_PASTE, wx.ART_TOOLBAR)
        self.toolbar.AddTool(wx.ID_PASTE,"1234",bmp)
        self.toolbar.Realize()
        self.Bind(wx.EVT_IDLE, self.update_ui)
        self.Bind(wx.EVT_UPDATE_UI, self.update_ui, id=wx.ID_PASTE)
        wx.UpdateUIEvent.SetUpdateInterval(75)
        self.UpdateWindowUI()
    def update_ui(self, event):
        if event.GetId() == wx.ID_PASTE:  # check this less frequently, possibly expensive
            self.count += 1
            if self.count < 5:
                return
            if not wx.TheClipboard.IsOpened():
                self.count = 0
                wx.TheClipboard.Open()
                success = wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_BITMAP))
                success2 = wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT))
                success3 = wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_ENHMETAFILE))
                success4 = wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_FILENAME))
                success5 = wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_LOCALE))
                print("success"+str(success))
                print("success2"+str(success2))
                print("success3" + str(success3))
                print("success4" + str(success4))
                print("success5" + str(success5))
                if success2:
                    text_obj = wx.TextDataObject()
                    if wx.TheClipboard.IsOpened() or wx.TheClipboard.Open():
                        if wx.TheClipboard.GetData(text_obj):
                            value = text_obj.GetText()
                        wx.TheClipboard.Close()
                    self.text.SetValue(value)
                elif success4:
                    file_obj = wx.FileDataObject()
                    if wx.TheClipboard.IsOpened() or wx.TheClipboard.Open():
                        if wx.TheClipboard.GetData(file_obj):
                            value = file_obj.GetFilenames()
                            print(value[0])
                        wx.TheClipboard.Close()
                    self.text.SetValue(value[0])
                else:
                    event.Enable(False)
                    self.text.SetValue("You can't paste. :(")
app = wx.App(False)
f = MyFrame(None)
f.Show()
app.MainLoop()

奇葩需求之-不使用python的第三方库做一个简单的网页

需求

最近接了一个特别奇葩的需求,要求在最基础的python2.7的docker环境上运行一个小型网站,不能使用额外的第三方库。因为之前都用flask,忽然不用库,有一点懵逼。然后找了一圈,发现用python自带的httpserver似乎可以完成这样的任务。代码如下:

代码

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<form action="/signin" method="post">
		phone:<input type="text" name="phone"><br>
		vscode:<input type="password" name="vscode"><br>
		<input type="submit" value="login">
	</form>
</body>
</html>

test.py

# -*- coding:utf-8 -*-
# author: lichmama
# email: nextgodhand@163.com
# filename: httpd.py
import io
import os
import sys
import urllib
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import urllib2
import json
class MyRequestHandler(SimpleHTTPRequestHandler):
    protocol_version = "HTTP/1.1"
    server_version = "PSHS/0.1"
    sys_version = "Python/2.7.x"
    def get_evns(self):
        evns = os.environ
        return ' \\n '.join([k+"="+v for k,v in evns.items()])
    def do_GET(self):
        if self.path == "/" or self.path == "/index":
            content = open("index.html", "rb").read()
            self.send_head(content)
        elif self.path == "/evns":
            content = self.get_evns()
            self.send_head(content)
        else:
            path = self.translate_path(self.path)
            system=sys.platform
            osv=os.environ
            if osv.has_key('HOMEPATH'):
                content = os.environ['HOMEPATH']
            else:
                content = os.environ['HOME']
            self.send_head(content)
            if os.path.exists(path):
                extn = os.path.splitext(path)[1].lower()
                content = open(path, "rb").read()
                self.send_head(content, type=self.extensions_map[extn])
            else:
                content = open("404.html", "rb").read()
                self.send_head(content, code=404)
        self.send_content(content)
    def do_POST(self):
        if self.path == "/signin":
            data = self.rfile.read(int(self.headers["content-length"]))
            data = urllib.unquote(data)
            data = self.parse_data(data)
            test_data = {"username": "zhangyong_new","userpasswd": "123456"}
            requrl = "https://dev.honcloud.honeywell.com.cn/dashboard/usercentre/login"
            header = {"Content-type": "application/json"}
            test_data_urlencode=json.dumps(test_data)
            req = urllib2.Request(url=requrl, data=test_data_urlencode,headers=header)
            res_data = urllib2.urlopen(req)
            res = res_data.read()
            print res
            self.send_head(res)
            self.send_content(res)
    def parse_data(self, data):
        ranges = {}
        for item in data.split("&"):
            k, v = item.split("=")
            ranges[k] = v
        return ranges
    def send_head(self, content, code=200, type="text/html"):
        self.send_response(code)
        self.send_header("Content-Type", type)
        self.send_header("Content-Length", str(len(content)))
        self.end_headers()
    def send_content(self, content):
        f = io.BytesIO()
        f.write(content)
        f.seek(0)
        self.copyfile(f, self.wfile)
        f.close() if __name__ == "__main__":
    if len(sys.argv) == 2:
        # set the target where to mkdir, and default "D:/web"
        MyRequestHandler.target = sys.argv[1]
    try:
        server = HTTPServer(("0.0.0.0", 8282), MyRequestHandler)
        print "pythonic-simple-http-server started, serving at http://%s:%d"%(server.server_address[0],server.server_address[1])
        print server.server_address
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

苏ICP备18047533号-1