使用Python編寫一個在Linux下實現截圖分享的指令碼的教程

來源:互聯網
上載者:User
引子

Linux下不支援QQ等功能豐富的IM,雖然可以通過wine運行QQ2012,但是還是喜歡在gtalk群中聊天,gtalk群不支援圖片方式,這就要靠我們大家自己來解決了,eleven開放了一個Image上傳和顯示介面,提供了使用curl來解決,但是我們公司的網路使用squid禁止了curl的訪問,所以整天看他們這麼爽的分享圖片我也不甘心阿,所以就使用Python寫了一個分享圖片的指令碼
實現

使用scrot,然後使用urllib2庫上傳圖片,如果存在PyQt4庫則會將結果放到剪貼簿上,如果不存在則輸出,自行複製
代碼

#!/usr/bin/env python# -*- coding:utf-8 -*-## Author : cold# E-mail : wh_linux@126.com# Date : 13/01/21 09:54:39# Desc : 貼代碼和圖片#import urllib2, jsonimport mimetoolsimport mimetypesimport itertools__host__ = "http://eleveni386.7axu.com"class Form(object): def __init__(self):  self.form_fields = []  self.files = []  self.boundary = mimetools.choose_boundary()  self.content_type = "application/x-www-form-urlencoded"  return def get_content_type(self):  return self.content_type def add_field(self, name, value):  self.form_fields.append((name, value))  return def add_file(self, fieldname, filename, fileHandle, mimetype=None):  body = fileHandle.read()  if mimetype is None:   mimetype = ( mimetypes.guess_type(filename)[0]       or       'applicatioin/octet-stream')  self.files.append((fieldname, filename, mimetype, body))  self.content_type = 'multipart/form-data; boundary=%s' % self.boundary  return def __str__(self):  parts = []  part_boundary = '--' + self.boundary  parts.extend(   [ part_boundary,    'Content-Disposition: form-data; name="%s"' % name,    '',    value,    ]   for name, value in self.form_fields)  if self.files:   parts.extend([    part_boundary,    'Content-Disposition: form-data; name="%s"; filename="%s"' %\    (field_name, filename),    'Content-Type: %s' % content_type,    '',    body,   ] for field_name, filename, content_type, body in self.files)  flattened = list(itertools.chain(*parts))  flattened.append('--' + self.boundary + '--')  flattened.append('')  return '\r\n'.join(flattened)class HttpHelper(object): def __init__(self, url = None, form = None, method = 'GET'):  self._url = url  self._form = form  self._body = str(form)  self._method = method  self._dst_url = None  if url:   self.make_request() def make_request(self):  url = self._url  if not self._url.startswith('http://'):   url = 'http://' + self._url  self.request = urllib2.Request(url)  if self._form:   self.add_header("Content-Type", self._form.get_content_type())   self.add_header("Content-Length", len(self._body))   self.request.add_data(self._body) def add_header(self, key, val):  self.request.add_header(key, val) def change(self, url, params = {}, method = 'GET'):  self._url = url  self._params = params  self._method = method  self.make_request() def open(self):  response = urllib2.urlopen(self.request)  content = response.read()  self._dst_url = response.geturl()  try:   return json.loads(content)  except:   return contentif __name__ == "__main__": import argparse import os parser = argparse.ArgumentParser() parser.add_argument(dest="path", nargs="?") args = parser.parse_args() if args.path:  path = args.path else:  path = r"/tmp/tmpscrot.png"  os.system("scrot -s {0}".format(path)) form = Form() filename = os.path.split(path)[-1] form.add_file(fieldname='mypic', filename=filename,     fileHandle=open(path)) http = HttpHelper( __host__ + '/Image/', form) url = http.open() try:  from PyQt4.QtGui import QApplication  app = QApplication([])  cb = QApplication.clipboard()  cb.setText(url) except:  print url

安裝

將上面代碼儲存一個檔案,放在PATH路徑裡,賦予執行許可權即可
使用

預設的不跟圖片地址則會,完畢後自動分享,如安裝了PyQt4庫則會將結果放到剪貼簿,如沒有則輸出結果.如果指令碼給了圖片路徑參數則上傳給定路徑的圖片

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.