how to install pythonwebkit and pywebkitgtk in ubuntu? - python

i am a new to use ubuntu.
i want to install pythonwebkit and pywebkitgtk in ubuntu,but i have tryed a long time. even thongth i can install,but,when i excute this code,
#!/usr/bin/env python
import pygtk
pygtk.require("2.0")
import gi
from gi.repository import WebKit as webkit, Gtk as gtk
dir(gtk)
print dir(gtk.WindowType)
init_string="""
<div id="testing">testing</div>
<div><button id="link">CLICK ME</button>
"""
class Browser:
# Ventana del programa
def __init__(self):
self.window = gtk.Window(type=gtk.WindowType.TOPLEVEL)
self.window.set_position(gtk.WindowPosition.CENTER)
self.window.set_default_size(800, 600)
self.window.fullscreen()
self.window.connect("destroy", self.on_quit)
# Un vBox, en la parte de arriba hay una caja para ingresar
# la direccion web, y abago se muestra la pagina
vbox = gtk.VBox()
# La parte en donde se muestra la pagina que se visita (con scroll incluido)
self.scroll_window = gtk.ScrolledWindow()
self.webview = webkit.WebView()
print dir(self.webview)
#self.scroll_window.add(self.webview)
# Unimos todo en el vBox
#vbox.pack_start(self.url_text, True, False, 0)
# El expand=False al empaquetarlo es para que el entry no ocupe media pantalla
#vbox.pack_start(self.scroll_window, True, True, 0)
#self.window.add(vbox)
self.window.add(self.webview)
self.window.show_all()
self.webview.load_string(init_string, "text/html", "utf-8", '#')
doc = self.webview.get_dom_document()
self.webview.connect('document-load-finished', self.onLoad)
print doc
print dir(doc)
def onLoad(self, param1, param2):
print "STARTING"
doc = self.webview.get_dom_document()
div = doc.get_element_by_id('testing')
print div
print dir(div)
print div.get_inner_html()
div.set_inner_html('DYNAMIC TEXT')
link = doc.get_element_by_id('link')
#print link
#print dir(link)
link.connect('click-event', self.onClick, link)
#div.connect_object('click-event', self.onClick, link)
def print_childs(self, elem):
childs = elem.get_child_nodes()
for c in range(childs.get_length()):
i=childs.item(c)
#print dir(i)
print "%s - %s\n" %(i.get_tag_name(), i.get_inner_html())
self.print_childs(i)
def onClick(self, p1, p2, p3=None):
print "CLICKED - %s %s %s " % (str(p1), str(p2), str(p3))
#return False
def on_quit(self, widget):
gtk.main_quit()
if __name__ == "__main__":
browser = Browser()
try:
while True:
gtk.main_iteration()
except:
gtk.quit()
print "BAILING OUT!"
the "doc = self.webview.get_dom_document()" can't pass,the error is webview does not have the get_dom_document attr.
what should i can do? i must access the dom tree, please!
i know the way i install pythonwebkit or pywebkitgtk has something wrong,but i can't do right.
is someone can help?

Run your import directives in the interpreter.
If that doesn't throw any exceptions (as I gather from where you say the error arises), then the problem is most likely not with installing the libraries, and has nothing to do with Ubuntu.
Python is not saying 'hey, this is not installed correctly', it's saying 'hey, you're handling this object incorrectly! The function you want to reach is not there!'.
Recheck the approapiate documentation, and see how to get the DOM tree.
edit -- I got this from a quick google query.
def _view_load_finished_cb(self, view, frame):
doc = frame.get_dom_document()
nodes = doc.getElementsByTagName('body')
body = nodes.item(0)
You're trying to access the DOM tree from an object that doesn't provide it.

Related

PyFirmata Button Doesnt Change Values

Im Using Pyfirmata For A While, And I Want To Connect A Joystick Button On It, I Made The Code (AI) And It Didnt Work, It Keeps Changing Like "True, False, False, True, True..." and doesnt do nothing, heres my python code (PS: im using standart_firmata)
from pyfirmata import *
import time
import speech_recognition as sr
import random
from math import *
class IA:
def __init__(self, board, maquina, analogx, analogy) -> None:
self.board = board
self.maquina = maquina
self.analogx = analogx
self.analogy = analogy
self.button = self.board.get_pin("d:8:i")
self.previous_button_state = 0
self.sr = sr.Recognizer()
def record(self):
with self.sr.Microphone() as source:
print("gravando")
self.sr.adjust_for_ambient_noise(source)
audio = self.sr.listen(source)
try:
frase = sr.recognize_google(audio,language='pt-BR')
frase = frase.lower()
pass
except sr.UnkownValueError:
self.maquina.say("Não Entendi")
self.maquina.runAndWait()
self.main()
if (frase == "olá"):
sentences = ["Olá","Opa","Eae","Oi","Haha Eae"]
sentence = random.choice(tuple(sentences))
self.maquina.say(sentence)
self.maquina.runAndWait()
def main(self):
while True:
print(floor(self.button.read()))
time.sleep(1)
def greet(self):
self.board.digital[2].write(135)
self.maquina.say("Olá! Sou Jesse, Bem Vindo Ao Meu Sistema")
self.maquina.runAndWait()
self.board.digital[2].write(90)
self.maquina.say("Posso Fazer Varias Coisas")
self.maquina.runAndWait()
self.board.digital[2].write(135)
self.maquina.say("Apenas Aperte No Botão Do Joystick E Fale Oque Quer! Divirta-se")
self.maquina.runAndWait()
self.board.digital[2].write(90)
self.board.digital[3].write(75)
self.main()
If anyone can help me, i will be grateful, thanks.

problem with send() function using socket in python

I'm using socket in python between 2 laptop to send informations. But I have an error and i can't resolve it. (I'm a debutant in python). The problem is when i trierd to send information with send() function
Traceback (most recent call last):
File "client.py", line 60, in <module>
client.send(GetMyInfo.scan())
TypeError: send() argument 1 must be string or buffer, not None
Maybe the error is due my function Getinfo ?
I'm using a class with functions (listinfo() here).
Thx
Here is the code :
import socket
import subprocess
import os,sys
#==========================================================================================
#creation d'une classe pour rendre le programme oriente objet
class GetInfo:
infos = os.uname()
currentUser = os.getlogin()
rep_actuel = os.getcwd()
myDirectory = os.listdir("/Users/")
def listInfo(self):
#afficher des informations sur le systeme
print "Informations du systeme :{} ".format(GetInfo.infos)
#afficher l'utilisateur actuel
print "Current user : {} \n".format(GetInfo.currentUser)
#afficher le path du repertoire actuel
print "Repertoire actuel : {} \n".format(GetInfo.rep_actuel)
def scan(self):
print "Liste de tous les repertoires dans Users/"
#on liste toutes les directories et sous directories
for file in GetInfo.myDirectory:
print file
#instance de l objet GetInfo (creation de l'objet)
GetMyInfo = GetInfo()
# afficage des infos de l'objet
#GetMyInfo.listInfo()
#GetMyInfo.scan()
#==========================================================================================
# on cree un objet socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "Socket successfully created"
# reservation d'un port specifique
port = 12345
# contient le nom d hote et le numero du port
#identifiant le serveur auquel on veut se connecter.
s.bind(('127.0.0.1', port))
print "socket binded to %s" %(port)
# activation du mode ecoute
# avec un nombre maximum de connexions qu il peut recevoir sur ce port sans les accepter
s.listen(5)
print "socket is listening"
#==========================================================================================
# gestion des erreurs
while True:
# on etabli la connection avec le client
client, addr = s.accept()
print 'Got connection from', addr
# send the informations about the victim.
client.send(GetMyInfo.scan())
print client.recvfrom(2048)
# on ferme la connection
s.close()

update json external file in python dialog

Hello I am developing an application in python, my problem is that I am saving a json file and I am calling it in a QlistWidget inside a Dialog
[
{
"title":"El titulo",
"enabled":true,
"path":"path",
"id":"5"
},
{
"title":"El titulo 2",
"enabled":true,
"path":"path",
"id":"555"
},
{
"title":"El recontra titulo",
"enabled":false,
"path":"path",
"id":"5555"
},
{
"title":"El titulo",
"enabled":true,
"path":"path",
"id":"5"
}
]
Here I have the program running, I read the data correctly and I show them in a QlistWidget when I enter the dialog
GUI
the problem is when I update the json add more items, I close the dialog and return open but the list is not updated
here I leave my code
import sys
import os
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QLabel, QAction, QMessageBox
from PyQt5 import uic
from PyQt5.QtGui import QIcon
import modules.db as DB
#DB = DB.DB()
#DB.jsonOpen()
#class Dialogo Items
class Dialogo(QDialog):
def __init__(self, item):
QDialog.__init__(self)
uic.loadUi("menu/" + item + ".ui", self)
if item == 'addItems':
items = DB.jsonOpen('items')
for p in items:
self.listitems.addItem(p['title'])
self.listitems.repaint()
self.saveitem.clicked.connect(self.save_items)
self.cancelbtn.clicked.connect(self.close_dialog)
def save_items(self):
data = DB.jsonOpen('items')
title = self.title.text()
id = self.id.text()
if self.status.isChecked():
enabled = True
else: enabled = False
data.append({
'id': id,
'title': title,
'path': 'path',
'enabled': enabled
})
DB.jsonSave(data, 'items')
self.title.setText("")
self.id.setText("")
self.status.setChecked(False)
def close_dialog(self):
self.hide()
#class heredada de QMainWindow (consturctor de ventanas) principal
class ventana(QMainWindow):
#metodo constructor
def __init__(self):
#Iniciar el objeto QMainWindow
QMainWindow.__init__(self)
#cargar la configuracion de archivo .ui
uic.loadUi("app.ui", self)
#//// Barra de menu y acciones ////#
#Onjeto menuBar
menu = self.menuBar()
#Menu Padre Inicio
menu_inicio = menu.addMenu("&Inicio")
menu_inicio_items = QAction(QIcon("icons/add.png"), "&Agregar Items", self)
menu_inicio_items.setShortcut("Ctrl+i") #atajo de teclado
self.DialogoItems = Dialogo('addItems'); # instanciamos la clase Dialogo Items
menu_inicio_items.triggered.connect(self.OpenDialogItems) #lanzados el dialogo item desde el menu items
menu_inicio.addAction(menu_inicio_items)
#Menu Configuracon
menu_conf = menu.addMenu("&Configuración")
#configuracion general
menu_conf_general = QAction(QIcon("icons/setting.png"), "&General", self)
self.DialogConfGeneral = Dialogo('confGeneral')
menu_conf_general.triggered.connect(self.OpenDialogConfGeneral) # lanazmos la configuracion general
menu_conf.addAction(menu_conf_general)
#configuracion servidores
menu_conf_servers = QAction(QIcon("icons/earth.png"), "&Servidores", self)
menu_conf_servers.setShortcut("Ctrl+h")
self.DialogConfServer = Dialogo('confServers')
menu_conf_servers.triggered.connect(self.OpenDialogConfServers)
menu_conf.addAction(menu_conf_servers)
#Abrir dialog Agregar Items
def OpenDialogItems(self):
self.DialogoItems.exec_()
#Abrir dialog Configuracion general
def OpenDialogConfGeneral(self):
self.DialogConfGeneral.exec_()
#Abrir dialog Configuracion Servidores
def OpenDialogConfServers(self):
self.DialogConfServer.exec_()
#instancia para iniciar una aplicacion
app = QApplication(sys.argv)
#app.setQuitOnLastWindowClosed(False)
#crear un objeto de la clase ventana
_ventana = ventana()
#mostrar ventana
_ventana.show()
app.exec_()
the save and read function works perfectly, the code of both
import os
import json
def jsonSave(data, file):
with open("data/"+file+".json", "w") as outfile:
json.dump(data, outfile)
def jsonOpen(file):
if os.path.exists('data/'+file+'.json') == True:
with open("data/"+file+".json", 'r') as json_file:
data = json.load(json_file)
else:
data = {}
data = []
return data
I'm using
- python 3
-pyQt5
The problem is caused by the fact that the data load is only given in the constructor, once the data is not updated since a new recharge is not done, what must be done is to create a method that the QListWidget must Reload whenever necessary or add the new item directly to the QListWidget, given the above, I have implemented the following code:
class Dialogo(QDialog):
def __init__(self, item):
QDialog.__init__(self)
uic.loadUi("menu/" + item + ".ui", self)
if item == 'addItems':
self.load()
self.saveitem.clicked.connect(self.save_items)
self.cancelbtn.clicked.connect(self.reject)
def load(self):
self.listitems.clear()
items = DB.jsonOpen('items')
for p in items:
self.listitems.addItem(p['title'])
def save_items(self):
data = DB.jsonOpen('items')
title = self.title.text()
id = self.id.text()
enabled = self.status.isChecked():
data.append({
'id': id,
'title': title,
'path': 'path',
'enabled': enabled
})
DB.jsonSave(data, 'items')
self.title.clear()
self.id.clear()
self.status.setChecked(False)
self.listitems.addItem(title)
# self.load()
I also recommend that if the data is going to be large it is not appropriate to save it in a json since it will see a great latency in the reading and writing of the data, the appropriate thing for those cases is to use a database, for example to use sqlite.

Building a server and client with xmlrpc in python

I'm trying to build a client and a server using xmlrpc in python, I HAVE to use a class named FunctionWrapper which has a method and the client use it, the method's name is sendMessage_wrapper(self, message), and the server is declared in another class, I'm trying to register the method in the server but when i call the method from de client I raise and error, can you help me, please?
Cliente:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from Constants.Constants import *
class MyApiClient:
def __init__(self, contact_port = DEFAULT_PORT,contact_ip=LOCALHOST_CLIENT):
self.contact_port = contact_port
self.contact_ip = contact_ip
self.proxy = xmlrpclib.ServerProxy(contact_ip+str(self.contact_port)+"/")
def sendMessage(self,message):
self.proxy.sendMessage_wrapper(message)
a = MyApiClient()
a.sendMessage("Hi")
a.sendMessage("WORKING")
Server:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from Constants.Constants import *
class MyApiServer:
def __init__(self,wrapper, my_port = DEFAULT_PORT):
self.port = my_port
self.server = SimpleXMLRPCServer((LOCALHOST,self.port))
self.wrapper = wrapper
self.server.register_instance(self.wrapper)
print("Running")
self.server.serve_forever()
class FunctionWrapper:
def __init__(self):
self.message = None
"""
Procedimiento que ofrece nuestro servidor, este metodo sera llamado
por el cliente con el que estamos hablando, debe de
hacer lo necesario para mostrar el texto en nuestra pantalla.
"""
def sendMessage_wrapper(self, message):
self.message = message
self.showMessage()
def showMessage(self):
print ("Mensaje "+self.message)
#raise NotImplementedError( "Should have implemented this" )
a = FunctionWrapper()
b = MyApiServer(a)
Here are the constants in case you need it
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#Nombres para etiquetas login local y remoto
MY_PORT_NUMBER_TITLE = "Cual es mi puerto?"
OTHER_PORT_NUMBER_TITLE = "Cual es el puerto de contacto?"
OTHER_IP_NUMBER_TITLE = "Cual es la direccion ip de contacto?"
LOGIN_TITLE = "Acceder"
#Nombres para las etiquetas del chat
CONVERSATION_TITLE = "Conversacion"
SEND_TITLE = "Responder"
#Titulo de las ventans GUI
LOGIN_WINDOW = "Login"
CHAT_WINDOW = "Chat"
#Modos de acceso al chat, local o remoto
LOCAL = "Local"
REMOTE = "Remote"
#Mensajes de error
WARNING = "¡Alerta!"
MISSING_MESSAGE = "No hay ningun mensaje para enviar"
#Localhost
LOCALHOST = "localhost"
DEFAULT_PORT = 5000
LOCALHOST_CLIENT = "http://localhost:"

Using asyncio to read the output of a serial port

I have been doing some port-reading for work, and I need to know if I should use asyncIO to read the data that comes in from this port.
Here's some details about the way in which the system is constructed.
Multiple sensors are being read at the same time and might produce output that goes in at the same time. (all data comes in through a probee ZU10 connected to a usb port) All data must be timestamped as soon as it comes in.
The data is supposed to be processed and then sent to a django webapp through a REST API.
The thing Is, it's really important not to lose any data, I'm asking about this because I believe there must be an easier way to do this than the one I'm thinking of.
The way I want the data to come in is through an asyncronous process that takes in the data into a queue and timestamps it, this way there is no way in which loss of data is present, and timestamping may be no more than a few fractions of a second off, which is not a problem.
If anyone has got any ideas I would be thankful for them
Here's the code I'm using to open the port, take the data in and what I've got so far on the actually reading the meaningful data.
Here's the reading part:
import serial #for port opening
import sys #for exceptions
#
#configure the serial connections (the parameters differs on the device you are connecting to)
class Serializer:
def __init__(self, port, baudrate=9600, timeout=.1):
self.port = serial.Serial(port = port, baudrate=baudrate,
timeout=timeout, writeTimeout=timeout)
def open(self):
''' Abre Puerto Serial'''
self.port.open()
def close(self):
''' Cierra Puerto Serial'''
self.port.close()
def send(self, msg):
''' envía mensaje a dispositivo serial'''
self.port.write(msg)
def recv(self):
''' lee salidas del dispositivo serial '''
return self.port.readline()
PORT = '/dev/ttyUSB0' #Esto puede necesitar cambiarse
# test main class made for testing
def main():
test_port = Serializer(port = PORT)
while True:
print(test_port.recv())
if __name__ == "__main__":
main()
And a bit of what I'm going to be using to filter out the meaningful reads (bear with it, it might be full of awful errors and maybe a terrible RegEx):
import re
from Lector import ChecaPuertos
from Lector import entrada
patterns = [r'^{5}[0-9],2[0-9a-fA-F] $'] #pattern list
class IterPat:
def __init__(self, lect, pat = patterns):
self.pat = pat # lista de patrones posibles para sensores
self.lect = lect # lectura siendo analizada
self.patLen = len(pat) #Largo de patrones
def __iter__(self):
self.iteracion = 0 #crea la variable a iterar.
def __next__(self):
'''
Primero revisa si ya pasamos por todas las iteraciones posibles
luego revisa si la iteración es la que pensabamos, de ser así regresa una
tupla con el patrón correspondiente, y la lectura
de otra forma para el valor de ser mostrado
'''
pattern = re.compile(self.pat[self.iteracion])
comp = pattern.match(self.lect)
if comp == True:
re_value = (self.pattern, self.lect)
return re_value
else:
self.iteración += 1
def main():
puerto = ChecaPuertos.serial_ports()
serial = entrada.Serializer(port = puerto[0])
if serial != open:
serial.open()
while True:
iter = IterPat()
#This is incomplete right here.
I am using asyncio to read/write a serial port with pyserial. I am having my device on the other end of the serial connection write a single byte when it is ready to receive a payload. Asyncio watches for that byte then sends the payload. It looks something like this:
serial_f = serial.Serial(port=dev, baudrate=BAUDRATE, timeout=2)
def write_serial():
status = serial_f.read(1)
serial_f.write(buffer)
loop = asyncio.get_event_loop()
loop.add_reader(serial_f.fileno(), write_serial)

Categories