I'm writing my first desktop app and I'm struggling with class instances. This app is a simple ftp program using paramiko. What I've set up so far is a connection.py which looks like this...
#connect.py
import user, db
import paramiko, time, os
paramiko.util.log_to_file('paramiko-log.txt')
class Connection:
def __init__(self):
#Call DB Functions
database = db.Database()
#Set Transport
self.transport = paramiko.Transport((user.hostname, user.port))
#User Credentials
username = user.username
password = user.password
self.transport.connect(username = username, password = password)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
print "Set your credentials in user.py for now!"
msg = "Connecting as: %s, on port number %d" % (user.username, user.port)
print msg
def disconnect(self):
print "Closing connection..."
self.sftp.close()
self.transport.close()
print "Connection closed."
Pretty straightforward. Connect and disconnect.
This connect.py file is being imported into a main.py (which is my gui)
#main.py
import connect
from PySide import QtCore, QtGui
class Window(QtGui.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
windowWidth = 550
windowHeight = 350
self.establishedConnection = ""
connectButton = self.createButton("&Connect", self.conn)
disconnectButton = self.createButton("&Disconnect", self.disconnect)
grid = QtGui.QGridLayout()
grid.addWidget(connectButton, 3, 3)
grid.addWidget(disconnectButton, 4, 3)
grid.addWidget(self.createList(), 1, 0, 1, 4)
self.setLayout(grid)
self.resize(windowWidth, windowHeight)
self.setWindowTitle("FTP Program")
def conn(self):
connection = connect.Connection()
self.establishedConnection = connection
def disconnect(self):
self.establishedConnection.disconnect()
def createButton(self, text, member):
button = QtGui.QPushButton(text)
button.clicked.connect(member)
return button
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
gui = Window()
gui.show()
sys.exit(app.exec_())
The issue is disconnecting.
I was thinking __init__ would create an instance of the Connection() class. If you look on main.py you can see that I tried to create the variable self.connectionEstablished in order to save the object so I could call disconnect on it later.
Where am I going wrong? I'm fairly new to python and other non-web languages(I spend most of my time writing RoR and php apps).
No errors are shown at any time and I started this app out as a terminal app so I do know that connect.py does work as intended.
Edit: So I guess Senderle got a connection closed message, which is what I'd like to see as well but I'm not. I'll mark a best answer if I see something that solves my problem.
Edit Solved: Pushed connect.py and main.py into one file to simplify things. And for some reason that solved things. So who knows whats going on. I'm still going to hold off on 'best answer'. If someone can tell me why I can't have a split file like that then I'm all ears.
I tried the code and it ran fine. I made only a few changes.
First, I didn't know what "user" and "db" are, so I commented out
import user, db
and
database = db.Database()
and used my own data for username, password, etc.
Second, the PySide module isn't available via my package manager, so I used PyQt4 instead. It didn't like grid.addWidget(self.createList(), 1, 0, 1, 4) so I commented that out, and everything worked as expected.
Further thoughts: When there were connection errors, there was some console feedback consisting of stack traces, but nothing more, and self.establishedConnection remained a string, causing self.establishedConnection.disconnect() to fail. So perhaps there's a connection problem?
EDIT: Aaaahhhhh, I just saw this: "No errors are shown at any time." Are you running this from a terminal or double-clicking an executable? If you start it from a terminal, I bet you'll see stacktraces in the terminal. The gui doesn't close when the code hits an exception.
EDIT2: If joining the files fixes the problem, then I am certain the problem cannot have anything to do with python itself. This has to be a problem with eclipse. You say that connection.py began as a terminal app, so you must be able to run python apps from the command line. Try the following: put main.py, connect.py, etc. in a directory of their own, open a terminal, and run python main.py. If it works as expected, then the problem has something to do with eclipse.
You are not calling conn() in the constructor.
Related
I am trying to connect to postgresql with qt. I managed that last one, but, just like in my previous question, an invisible internal error occurs. The difference is that now it happens when a query fails (for example, when the table does not exist).
The program should print None to the screen. But the program ends before that. Exactly when I call obj.prepare(query).
This is my code:
from PySide2.QtSql import QSqlDatabase, QSqlQuery
from PySide2.QtWidgets import QApplication, QMainWindow
app = QApplication([])
class SqlError(Exception):
pass
def connect(host, port, dbname, user, password):
db = QSqlDatabase.addDatabase("QPSQL")
db.setHostName(host)
db.setPort(port)
db.setDatabaseName(dbname)
if(not db.open(user, password)):
raise SqlError(db.lastError().text())
def execute(query, *args, **kwargs):
obj = QSqlQuery()
if(not obj.prepare(query)):
raise SqlError(obj.lastError().text())
if(kwargs):
for var, value in kwargs.items():
obj.bindValue(var, value)
elif(args):
for value in args:
obj.addBindValue(value)
if(not obj.exec_()):
raise SqlError(obj.lastError().text())
connect(host="localhost",
port=0,
dbname="mydatabase",
user="user",
password="password")
print(execute("SELECT * FROM c_venta"))
Attached screenshot of my idle. This behavior is similar to what happens when running from cmd and importing my script from the interpreter.
What do I need to catch that error, what am I doing wrong?
I've looked at several tutorials and I'm doing the same.
Edit: I tried the script importing it from the interpreter and it closes said interpreter without saying anything.
Edit 2: I tried variants of a certain answer and it didn't work for me either. https://stackoverflow.com/a/33741755/12913664
Edit 3: Pass the result of QSqlDatabase.database() to QSqlQuery (same result), to prepare (says it only accepts one argument), and tried saving the connection to a global variable and using db.exec (same result).
I am trying to write a Hexchat plugin in Python, which would start a server and then communicate with it using DBus and python-dbus library. Everything works fine, until I try to unload the plugin or close Hexchat (which unloads all plugins). The application freezes. It does not happen if I do not call any method using the DBus.
I tried to pinpoint the problem, so I have created a minimal example:
server.py
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
class EchoService(dbus.service.Object):
def __init__(self):
DBusGMainLoop(set_as_default=True)
self.loop = GLib.MainLoop()
bus_name = dbus.service.BusName(name='com.skontar.Echo', bus=dbus.SessionBus())
super().__init__(conn=None, object_path='/com/skontar/Echo', bus_name=bus_name)
def run(self):
self.loop.run()
#dbus.service.method(dbus_interface='com.skontar.Echo', in_signature='', out_signature='')
def quit(self):
self.loop.quit()
#dbus.service.method(dbus_interface='com.skontar.Echo', in_signature='s', out_signature='s')
def echo(self, text):
print(text)
return 'ACK'
EchoService().run()
dbus_plugin_unload_test.py
import subprocess
import time
import dbus
import hexchat
__module_name__ = 'dbus_plugin_unload_test'
__module_description__ = 'TBD'
__module_version__ = '1.0'
def get_dbus_interface():
session_bus = dbus.SessionBus()
dbus_object = session_bus.get_object(bus_name='com.skontar.Echo',
object_path='/com/skontar/Echo')
interface = dbus.Interface(object=dbus_object, dbus_interface='com.skontar.Echo')
return interface
def unload(userdata):
hexchat.prnt('Unloading {}, version {}'.format(__module_name__, __module_version__))
global interface
interface.quit()
time.sleep(1)
# raise Exception
hexchat.prnt('Loading {}, version {}'.format(__module_name__, __module_version__))
subprocess.Popen('python3 /home/skontar/Python/Examples/DBus/server.py', shell=True)
time.sleep(1)
interface = get_dbus_interface()
time.sleep(1)
interface.echo('TEST')
hexchat.hook_unload(unload)
In this example, everything works. When I try to unload the plugin or close Hexchat, server exits (so the .quit call works), but Hexchat hangs.
If I comment out both interface.echo('TEST') and interface.quit() it unloads fine, but also the plugin does not do anything useful. I have also found that if I raise Exception at the end of unload callback, everything closes "correctly", nothing hangs.
I am thinking that maybe I am supposed to do some DBus cleanup? Or am I missing some nuance of Hexchat plugin system? If I try the same with regular Python code outside the plugin system, both server and client exit just fine.
Okay, time for another question/post...
So currently i am trying to develop a simple python program that has a webkit/ webpage view and a serial port interface.. Not that it should matter, but this is also running on a raspberry pi.
The following code works fine.. But it will freeze the system as soon as i uncomment the serial port line that you can see commented out.
The day has been long and this one for some reason has my brain fried.. Python is not my strongest point, but mind you this is just a quick test script for now... Yes i have used google and other resources...
#!/usr/bin/env python
import sys
import serial
import threading
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
sURL = ""
sURL2 = ""
objSerial = serial.Serial(0)
def SerialLooper():
global objSerial
if objSerial.isOpen() == True:
print("is_responding")
#objSerial.write("is_responding")
time.sleep(10)
SerialLooper()
class TestCLASS(object):
def __init__(self):
global sURL
global sURL2
global objSerial
objSerial = serial.Serial(0)
sURL = "http://localhost/tester"
app = QApplication(sys.argv)
webMain = QWebView()
webMain.loadFinished.connect(self.load_finished)
webMain.load(QUrl(sURL))
webMain.show()
thread = threading.Thread(target=SerialLooper)
thread.start()
sys.exit(app.exec_())
def load_finished(boolNoErrors):
global sURL
print("Url - " + sURL)
#something here
#something else here
newObjClass = TestCLASS()
EDIT
Futher on this, it appears its not the multithreading but the serial.write()
It has been a while since I used serial, but IIRC it is not threadsafe (on Windows at least). You are opening the port in the main thread and performing a write in another thread. It's a bad practice anyway. You might also consider writing a simple single-threaded program to see if the serial port is actually working.
PS Your program structure could use some work. You only need one of the global statements (global objSerial), the rest do nothing. It would be better to get rid of that one, too.
And the recursive call to SerialLooper() will eventually fail when the recursion depth is exceeded; why not just use a while loop...
def SerialLooper():
while objSerial().isOpen(): # Drop the == True
# print something
# write to the port
# Sleep or do whatever
I have a very short PyQt program (n.b. that is a PythonFiddle link - this seems to crash horribly in Firefox, so code is also posted below) which prints output to a QTextEdit (using code from this SO answer). When I run the code (on Windows), it results in an APPCRASH. Some observations:
if I add a time.sleep call (i.e. uncomment out line 53), then the program completes fine
if I don’t redirect the output to the QEdit (i.e. comment out line 34) then it works regardless of whether the time.sleep call is commented out or not
I assume that this implies that the code redirecting the stdout is broken somehow - but I'm struggling to understand what's wrong with it to result in this behaviour - any pointers gratefully received!
Full error message
Problem signature:
Problem Event Name: APPCRASH
Application Name: pythonw.exe
Application Version: 0.0.0.0
Application Timestamp: 5193f3be
Fault Module Name: QtGui4.dll
Fault Module Version: 4.8.5.0
Fault Module Timestamp: 52133a81
Exception Code: c00000fd
Exception Offset: 00000000005cbdb7
OS Version: 6.1.7601.2.1.0.256.48
Locale ID: 2057
Additional Information 1: 5c9c
Additional Information 2: 5c9c27bb85eb40149b414993f172d16f
Additional Information 3: bc7e
Additional Information 4: bc7e721eaea1ec56417325adaec101aa
Pythonfiddle crashes horribly on Firefox (for me at least), so code below too:
import os, sys, time, calendar, math
from PyQt4 import QtCore, QtGui
class EmittingStream(QtCore.QObject):
textWritten = QtCore.pyqtSignal(str)
def write(self, text): self.textWritten.emit(str(text))
class myWrapper(QtGui.QMainWindow):
def __init__(self):
super(myWrapper, self).__init__()
self.toolbar = self.addToolBar("MainMenu")
self.toolbar.addAction(QtGui.QAction("myProg", self, triggered=self.myProgActions))
def myProgActions(self): self.setCentralWidget(myWidget())
class myWidget(QtGui.QWidget):
def __init__(self):
super(myWidget, self).__init__()
self.myBtn = QtGui.QPushButton('Run!', self)
self.myBtn.clicked.connect(self.startTest)
self.outputViewer = QtGui.QTextEdit()
self.grid = QtGui.QGridLayout()
self.grid.addWidget(self.myBtn)
self.grid.addWidget(self.outputViewer)
self.setLayout(self.grid)
def startTest(self):
self.myLongTask = TaskThread()
sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
self.myLongTask.start()
def normalOutputWritten(self, text):
cursor = self.outputViewer.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
cursor.insertText(text)
self.outputViewer.setTextCursor(cursor)
self.outputViewer.ensureCursorVisible()
QtGui.qApp.processEvents()
class TaskThread(QtCore.QThread):
def __init__(self): super(TaskThread, self).__init__()
def run(self): myProgClass()
class myProgClass:
def __init__(self):
for i in range(0,100):
print "thread", i+1, " ", math.sqrt(i)
#time.sleep(0.005)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
myApp = myWrapper()
myApp.show()
sys.exit(app.exec_())
Ok, one thing first about the thread safety of your program. Because you are connecting a QObject to stdout, calls to print will interact with this QObject. But you should only interact with a QObject from the thread it was created in. The implementation you have is potentially thread unsafe if you call print from a thread other than the one the QObject resides in.
In your case, you are calling print from a QThread while the EmmittingStream(QObject) resides in the main thread. I suggest you thus change your code to make it threadsafe, like so:
self.myLongTask = TaskThread()
sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
sys.stdout.moveToThread(self.myLongTask)
self.myLongTask.start()
Note that now calling print from the MainThread of your application will result in thread-unsafe behaviour. Since you aren't doing that at the moment, you are OK for now, but be warned!
I really suggest you read http://qt-project.org/doc/qt-4.8/threads-qobject.html and get your head around everything it talks about. Understanding that document is the key to avoiding annoying crashes due to threads.
--
Now, The issue with the crash is apparently caused by your call to processEvents(). I haven't worked out why (I imagine it is related to threads somehow...), but I can tell you that you do not need that line! Because you are using signals/slots, once the normalOutputWritten method runs, control returns to the Qt Event Loop anyway, and it will continue to process events as normal. There is thus no need to force Qt to process events!
Hope that helps!
EDIT: For an example of how to make your EmittingStream/print calls thread-safe, see here: Redirecting stdout and stderr to a PyQt4 QTextEdit from a secondary thread
I'm trying a to create a basic media player using libvlc which will be controlled through dbus. I'm using the gtk and libvlc bindings for python. The code is based on the official example from the vlc website
The only thing I modified is to add the dbus interface to the vlc instance
# Create a single vlc.Instance() to be shared by (possible) multiple players.
instance = vlc.Instance()
print vlc.libvlc_add_intf(instance, "dbus"); // this is what i added. // returns 0 which is ok
All is well, the demo works and plays any video files. but for some reason the dbus control module doesn't work (I can't believe I just said the dreaded "doesn't work" words):
I already have the working client dbus code which binds to the MPRIS 2 interface. I can control a normal instance of a VLC media player - that works just fine, but with the above example nothing happens. The dbus control module is loaded properly, since libvlc_add_intf doesn't return an error and i can see the MPRIS 2 service in D-Feet (org.mpris.MediaPlayer2.vlc).
Even in D-Feet, trying to call any of the methods of the dbus vlc object returns no error but nothing happens.
Do I need to configure something else in order to make the dbus module control the libvlc player?
Thanks
UPDATE
It seems that creating the vlc Instance and setting a higher verbosity, shows that the DBus calls are received but they have no effect whatsoever on the player itself.
Also, adding the RC interface to the instance instead of DBus, has some problems too: When I run the example from the command line it drops me to the RC interface console where i can type the control commands, but it has the same behaviour as DBus - nothing happens, no error, nada, absolutely nothing. It ignores the commands completely.
Any thoughts?
UPDATE 2
Here is the code that uses libvlc to create a basic player:
from dbus.mainloop.glib import DBusGMainLoop
import gtk
import gobject
import sys
import vlc
from gettext import gettext as _
# Create a single vlc.Instance() to be shared by (possible) multiple players.
instance = vlc.Instance("--one-instance --verbose 2")
class VLCWidget(gtk.DrawingArea):
"""Simple VLC widget.
Its player can be controlled through the 'player' attribute, which
is a vlc.MediaPlayer() instance.
"""
def __init__(self, *p):
gtk.DrawingArea.__init__(self)
self.player = instance.media_player_new()
def handle_embed(*args):
if sys.platform == 'win32':
self.player.set_hwnd(self.window.handle)
else:
self.player.set_xwindow(self.window.xid)
return True
self.connect("map", handle_embed)
self.set_size_request(640, 480)
class VideoPlayer:
"""Example simple video player.
"""
def __init__(self):
self.vlc = VLCWidget()
def main(self, fname):
self.vlc.player.set_media(instance.media_new(fname))
w = gtk.Window()
w.add(self.vlc)
w.show_all()
w.connect("destroy", gtk.main_quit)
self.vlc.player.play()
DBusGMainLoop(set_as_default = True)
gtk.gdk.threads_init()
gobject.MainLoop().run()
if __name__ == '__main__':
if not sys.argv[1:]:
print "You must provide at least 1 movie filename"
sys.exit(1)
if len(sys.argv[1:]) == 1:
# Only 1 file. Simple interface
p=VideoPlayer()
p.main(sys.argv[1])
the script can be run from the command line like:
python example_vlc.py file.avi
The client code which connects to the vlc dbus object is too long to post so instead pretend that i'm using D-Feet to get the bus connection and post messages to it.
Once the example is running, i can see the players dbus interface in d-feet, but i am unable to control it. Is there anything else that i should add to the code above to make it work?
I can't see your implementation of your event loop, so it's hard to tell what might be causing commands to not be recognized or to be dropped. Is it possible your threads are losing the stacktrace information and are actually throwing exceptions?
You might get more responses if you added either a psuedo-code version of your event loop and DBus command parsing or a simplified version?
The working programs found on nullege.com use ctypes. One which acted as a server used rpyc. Ignoring that one.
The advantages of ctypes over dbus is a huge speed advantage (calling the C library code, not interacting using python) as well as not requiring the library to implement the dbus interface.
Didn't find any examples using gtk or dbus ;-(
Notable examples
PyNuvo vlc.py
Milonga Tango DJing program
Using dbus / gtk
dbus uses gobject mainloop, not gtk mainloop. Totally different beasts. Don't cross the streams! Some fixes:
Don't need this. Threads are evil.
gtk.gdk.threads_init()
gtk.main_quit() shouldn't work when using gobject Mainloop. gobject mainloop can't live within ur class.
if __name__ == '__main__':
loop = gobject.MainLoop()
loop.run()
Pass in loop into ur class. Then call to quit the app
loop.quit()
dbus (notify) / gtk working example
Not going to write ur vlc app for u. But here is a working example of using dbus / gtk. Just adapt to vlc. Assumed u took my advise on gtk above. As u know any instance of DesktopNotify must be called while using gobject.Mainloop . But u can place it anywhere within ur main class.
desktop_notify.py
from __future__ import print_function
import gobject
import time, dbus
from dbus.exceptions import DBusException
from dbus.mainloop.glib import DBusGMainLoop
class DesktopNotify(object):
""" Notify-OSD ubuntu's implementation has a 20 message limit. U've been warned. When queue is full, delete old message before adding new messages."""
#Static variables
dbus_loop = None
dbus_proxy = None
dbus_interface = None
loop = None
#property
def dbus_name(self):
return ("org.freedesktop.Notifications")
#property
def dbus_path(self):
return ("/org/freedesktop/Notifications")
#property
def dbus_interface(self):
return self.dbus_name
def __init__(self, strInit="initializing passive notification messaging")
strProxyInterface = "<class 'dbus.proxies.Interface'>"
""" Reinitializing dbus when making a 2nd class instance would be bad"""
if str(type(DesktopNotify.dbus_interface)) != strProxyInterface:
DesktopNotify.dbus_loop = DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus(mainloop=DesktopNotify.dbus_loop)
DesktopNotify.dbus_proxy = bus.get_object(self.dbus_name, self.dbus_path)
DesktopNotify.dbus_interface = dbus.Interface(DesktopNotify.dbus_proxy, self.dbus_interface )
DesktopNotify.dbus_proxy.connect_to_signal("NotificationClosed", self.handle_closed)
def handle_closed(self, *arg, **kwargs):
""" Notification closed by user or by code. Print message or not"""
lngNotificationId = int(arg[0])
lngReason = int(arg[1])
def pop(self, lngID):
""" ID stored in database, but i'm going to skip this and keep it simple"""
try:
DesktopNotify.dbus_interface.CloseNotification(lngID)
except DBusException as why:
print(self.__class__.__name__ + ".pop probably no message with id, lngID, why)
finally:
pass
def push(self, strMsgTitle, strMsg, dictField):
""" Create a new passive notification (took out retrying and handling full queues)"""
now = time.localtime( time.time() )
strMsgTime = strMsg + " " + time.asctime(now)
del now
strMsgTime = strMsgTime % dictField
app_name="[your app name]"
app_icon = ''
actions = ''
hint = ''
expire_timeout = 10000 #Use seconds * 1000
summary = strMsgTitle
body = strMsgTime
lngNotificationID = None
try:
lngNotificationID = DesktopNotify.dbus_interfacec.Notify(app_name, 0, app_icon, summary, body, actions, hint, expire_timeout)
except DBusException as why:
#Excellent spot to delete oldest notification and then retry
print(self.__class__.__name__ + ".push Being lazy. Posting passive notification was unsuccessful.", why)
finally:
#Excellent spot to add to database upon success
pass