I am using "Inotify" to logs event when a file or folder is created in a directory ( tmp here) . The example here does the job in as serial process. Meaning, All file creation are treated one after the other, in a sequential way.
import logging
import inotify.adapters
_DEFAULT_LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
_LOGGER = logging.getLogger(__name__)
def _configure_logging():
_LOGGER.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
formatter = logging.Formatter(_DEFAULT_LOG_FORMAT)
ch.setFormatter(formatter)
_LOGGER.addHandler(ch)
def _main():
i = inotify.adapters.Inotify()
i.add_watch(b'/tmp')
try:
for event in i.event_gen():
if event is not None:
(header, type_names, watch_path, filename) = event
_LOGGER.info("WD=(%d) MASK=(%d) COOKIE=(%d) LEN=(%d) MASK->NAMES=%s "
"WATCH-PATH=[%s] FILENAME=[%s]",
header.wd, header.mask, header.cookie, header.len, type_names,
watch_path.decode('utf-8'), filename.decode('utf-8'))
finally:
i.remove_watch(b'/tmp')
if __name__ == '__main__':
_configure_logging()
_main()
I would like to introduce parallelization of the events notification in case of several files are uploaded by importing threading, should I add a threading as loop ?
Second concern, I am not sure where it would make sens to put the thread function.
The below scripts handles multiples events in case of multiples sessions. So in my case, this is enough. I Added the multiprocessing option instead of threading. I found multiprocessing faster than threading.
import logging
import threading
import inotify.adapters
import multiprocessing
_DEFAULT_LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
_LOGGER = logging.getLogger(__name__)
def _configure_logging():
_LOGGER.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
formatter = logging.Formatter(_DEFAULT_LOG_FORMAT)
ch.setFormatter(formatter)
_LOGGER.addHandler(ch)
def PopUpMessage (event):
if event is not None:
(header, type_names, watch_path, filename) = event
_LOGGER.info("WD=(%d) MASK=(%d) COOKIE=(%d) LEN=(%d) MASK->NAMES=%s "
"WATCH-PATH=[%s] FILENAME=[%s]",
header.wd, header.mask, header.cookie, header.len, type_names,
watch_path.decode('utf-8'), filename.decode('utf-8'))
def My_main(count):
i = inotify.adapters.Inotify()
DirWatcher=i.add_watch(b'/PARA')
try:
while True:
for event in i.event_gen():
m = multiprocessing.Process(target=PopUpMessage, args=(event,))
m.start()
finally:
i.remove_watch(b'/PARA')
if __name__ == '__main__':
_configure_logging()
N = multiprocessing.Process(target=My_main)
N.start()
Related
I have a little GUI Program that should only get some inputs to use these inputs for a method call.
Therefore I have several tk.Entry objects. Now my method that I want to execute needs a file from my hard disk. I want to scrape it with ElementTree. (I think the file needs to be in the same directory as my .py file? If not please tell me how to use a file from another path). My Idea was to copy that file into the current filepath and then only use a simple call to get access to this file.
But when I want to copy this file it is getting copied after I close the program and that should not happen. It should instantly copy the file so I can work with it.
Is there a way to refresh my files or do you have another idea?
Thank you and here is my code:
from Modules import copy_file
import tkinter as tk
class MainApplication(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
for Frame in (StartPage, SuccessPage):
page_name = Frame.__name__
frame = Frame(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
# method to show frames
def show_frame(self, page_name):
frame = self.frames[page_name] #getting our frame from our frames list
frame.tkraise() #raise it up to the front
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
# Open File Button
self.button_open_file = ttk.Button(self, text = "Open File", command = self.get_file_directory).grid(row=5, column=0, sticky="WE")
def get_file_directory(self):
filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("all files","*.*"),("jpeg files","*.jpg")))
copy_file(filename)
class SuccessPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
# Open File Button
self.label = tk.Label(self, text = "Lab").grid(row=0 column=0, sticky="WE")
if __name__ == '__main__':
application = MainApplication().mainloop()
----------------------------------------------------------------------------------------------
Modules.py
from shutil import copy
def copy_file(src):
destination_path = os.path.dirname(os.path.realpath(__file__))
copy(src, destination_path)
I am trying to create a tkinter page that shows the time and it should be constantly updated. I have tried:
from tkinter.font import *
import time
def SetTime():
global time_date
time_date = time.strftime("%H:%M")
InfoTime.set(time_date)
Main = Tk()
Main.geometry("1600x1200")
Main.title("Time")
FontStyle = Font(family = "Times New Roman", size = 48)
InfoTime = StringVar()
TitleText = Label(Main,textvariable = InfoTime,font = FontStyle).pack()
while True:
SetTime()
However, running the
While True: line and running
SetTime()
constantly is for some reason preventing the tkinter page (Main) from opening. This has been a problem for a lot of my tkinter projects.
Please note, I am running python 3.7.2 in IDLE.
Thanks.
This should do it:
from tkinter import *
from tkinter.font import *
import time
Main = Tk()
Main.geometry("1600x1200")
Main.title("Time")
FontStyle = Font(family = "Times New Roman", size = 48)
TitleText = Label(Main, font = FontStyle)
TitleText.pack()
time_date1 = ''
def SetTime():
global time_date1
global TitleText
# Gets current time
time_date2 = time.strftime("%H:%M")
# If time has changed, update it
if time_date2 != time_date1:
time_date1 = time_date2
TitleText.config(text=time_date2)
# Repeats function every 200 milliseconds
TitleText.after(200, SetTime)
SetTime()
Main.mainloop()
The comments pretty much explain everything. I also cleaned up and reformatted your code to make it look nicer.
I'm trying to attach a reactivestream subscriber to an akka source.
My source seems to work fine with a simple sink (like a foreach) - but if I put in a real sink, made from a subscriber, I don't get anything.
My context is:
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}
import org.reactivestreams.{Subscriber, Subscription}
implicit val system = ActorSystem.create("test")
implicit val materializer = ActorMaterializer.create(system)
class PrintSubscriber extends Subscriber[String] {
override def onError(t: Throwable): Unit = {}
override def onSubscribe(s: Subscription): Unit = {}
override def onComplete(): Unit = {}
override def onNext(t: String): Unit = {
println(t)
}
}
and my test case is:
val subscriber = new PrintSubscriber()
val sink = Sink.fromSubscriber(subscriber)
val source2 = Source.fromIterator(() => Iterator("aaa", "bbb", "ccc"))
val source1 = Source.fromIterator(() => Iterator("xxx", "yyy", "zzz"))
source1.to(sink).run()(materializer)
source2.runForeach(println)
I get output:
aaa
bbb
ccc
Why don't I get xxx, yyy, and zzz?
Citing the Reactive Streams specs for the Subscriber below:
Will receive call to onSubscribe(Subscription) once after passing an
instance of Subscriber to Publisher.subscribe(Subscriber). No further
notifications will be received until Subscription.request(long) is
called.
The smallest change you can make to see some items flowing through to your subscriber is
override def onSubscribe(s: Subscription): Unit = {
s.request(3)
}
However, keep in mind this won't make it fully compliant to the Reactive Streams specs. It being not-so-easy to implement is the main reason behind higher level toolkits like Akka-Streams itself.
I am wondering where are output functions of NAO behavior boxes usually defined.
I simply failed to find any related documentation in API. There are some you can find indeed, but not for output functions.
Take Speech Reco box for example, I can find definition of function "WordRecognized" on online API, but not the "wordRecognized" (case sensitive) and the "onNothing". Intuition is that they define them as helpers in the script of the box (which you can get by double-clicking on the box), but I just failed to find any relevant implementation of those either in the script.
Anyone had this before and know the solution? I really appreciate any feedback since I want to inspect how they are defined.
Code for Speech Reco is as below, and this situation happens for some other boxes too:
class MyClass(GeneratedClass):
def __init__(self):
GeneratedClass.__init__(self, False)
try:
self.asr = ALProxy("ALSpeechRecognition")
except Exception as e:
self.asr = None
self.logger.error(e)
self.memory = ALProxy("ALMemory")
def onLoad(self):
from threading import Lock
self.bIsRunning = False
self.mutex = Lock()
self.hasPushed = False
self.hasSubscribed = False
self.BIND_PYTHON(self.getName(), "onWordRecognized")
def onUnload(self):
from threading import Lock
self.mutex.acquire()
try:
if (self.bIsRunning):
if (self.hasSubscribed):
self.memory.unsubscribeToEvent("WordRecognized", self.getName())
if (self.hasPushed and self.asr):
self.asr.popContexts()
except RuntimeError, e:
self.mutex.release()
raise e
self.bIsRunning = False;
self.mutex.release()
def onInput_onStart(self):
from threading import Lock
self.mutex.acquire()
if(self.bIsRunning):
self.mutex.release()
return
self.bIsRunning = True
try:
if self.asr:
self.asr.setVisualExpression(self.getParameter("Visual expression"))
self.asr.pushContexts()
self.hasPushed = True
if self.asr:
self.asr.setVocabulary( self.getParameter("Word list").split(';'), self.getParameter("Enable word spotting") )
self.memory.subscribeToEvent("WordRecognized", self.getName(), "onWordRecognized")
self.hasSubscribed = True
except RuntimeError, e:
self.mutex.release()
self.onUnload()
raise e
self.mutex.release()
def onInput_onStop(self):
if( self.bIsRunning ):
self.onUnload()
self.onStopped()
def onWordRecognized(self, key, value, message):
if(len(value) > 1 and value[1] >= self.getParameter("Confidence threshold (%)")/100.):
self.wordRecognized(value[0]) #~ activate output of the box
else:
self.onNothing()
Those methods are defined when you create or edit a box input or output. See this piece of documentation.
If you give the input the name "onMyTruc", then the method onInput_onMyTruc(self) will be called when the input is triggered.
If you give the name "output_value" to some output, it will create a callable method name: self.output_value()
In your example, wordRecognized and onNothing are the name of the output of the SpeechReco box.
i am trying to make a UI that display folders from a given directory,
and the user can check or uncheck the folder.
i would like to get the information of what was checked and return the folder
i know i can loop / iterate in a QTableWidget, but if its a view, or its comming from a Qt.Dir how its done?
(even might be a easier way to add the check boxes to the dir view model than making another class)
thanks.
from PyQt4 import QtCore, QtGui
import sys
import argparse
def parseOpt():
parser = argparse.ArgumentParser(description="Check if the files in this folder are valid EXRs")
parser.add_argument("-file", dest="filepath", help="The file path to be checked.")
return parser.parse_args()
ARGS = parseOpt()
class CheckableDirModel(QtGui.QDirModel):
#a class to put checkbox on the folders
def __init__(self, parent=None):
QtGui.QDirModel.__init__(self, None)
self.checks = {}
def data(self, index, role=QtCore.Qt.DisplayRole):
if role != QtCore.Qt.CheckStateRole:
return QtGui.QDirModel.data(self, index, role)
else:
if index.column() == 0:
return self.checkState(index)
def flags(self, index):
return QtGui.QDirModel.flags(self, index) | QtCore.Qt.ItemIsUserCheckable
def checkState(self, index):
if index in self.checks:
return self.checks[index]
else:
return QtCore.Qt.Unchecked
def setData(self, index, value, role):
if (role == QtCore.Qt.CheckStateRole and index.column() == 0):
self.checks[index] = value
self.emit(QtCore.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index)
return True
return QtGui.QDirModel.setData(self, index, value, role)
#def filtering(self, index):
# self.checks.setFilter(QtCore.QDir.Dirs|QtCore.QDir.NoDotAndDotDot)
class Ui_Dialog(QtGui.QDialog):
def __init__(self,parent=None):
QtGui.QDialog.__init__(self,parent)
self.setObjectName("Dialog")
self.resize(600, 500)
self.llayout = QtGui.QVBoxLayout(parent)
self.model = CheckableDirModel()
self.model.setFilter(QtCore.QDir.Dirs|QtCore.QDir.NoDotAndDotDot)
#self.tree = QtGui.QTreeWidget()
self.tree = QtGui.QTreeView()
self.tree.setModel(self.model)
self.tree.setSortingEnabled(True)
self.tree.setRootIndex(self.model.index(ARGS.filepath))
#self.tree.hideColumn(1)
#self.tree.hideColumn(2)
#self.tree.hideColumn(3)
self.tree.setWindowTitle("Dir View")
self.tree.resize(400, 480)
self.tree.setColumnWidth(0,200)
self.but = QtGui.QPushButton(QtCore.QString("Run"))
self.llayout.addWidget(self.tree)
self.llayout.addWidget(self.but)
self.setLayout(self.llayout)
self.but.clicked.connect(self.print_path)
def print_path(self):
print "hello"
root = self.tree.childCount()
print root
for i in range(root):
print i.text()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
ui = Ui_Dialog()
ui.show()
sys.exit(app.exec_())
If I understand you correctly, what you want is to replace your print_path method with the following:
def print_path(self):
print "hello"
for index,value in self.model.checks.items():
if value.toBool():
print self.model.filePath(index)