Sending emails in python while using PyHook in intervals - python

I'm using pyHook to hook the keyboard and the mouse actions. A log of the hooks is being created while the program is running. I want to send the log to an email every 5 minutes - while the PunpMessages is still working and the hooking action is still running. I know how to send emails in python, however, I don't know how to do it every fixed interval.

you can try python schedulers to call your methods on given interval.
You may want to look at this module:
http://packages.python.org/APScheduler/

Related

Best (easiest) way to execute a function (with response) in another python thread?

I have a little python script running on an raspberry pi (which is hooked up to detect if something is delivered to my mailbox) to send me a telegram message with a snapshot of my mailbox content.
Up until now this has been a single monolithic script which handled GPIO interaction (led lights and threaded_callbacks for reed_contacts), picamera and the telegram messaging.
But the telegram bot I was using (telepot) is no longer supported. Which is why I am looking to incorporate another python telegram bot implementation (python-telegram-bot) as well as migrate the script to python3 since python2 has also been discontinued.
But in doing so, I think I will need to split up the script, since the python-telegram-bot does not run non-blocking in a calling script.
In my old script I could still continue with the main program after calling the MessageLoop(bot, handler).run_as_thread()(spawning a separate background thread for update checking). But with the python-telegram-bot no instruction after
updater.start_polling() updater.idle() is evaluated till the bot is stopped.
I think my best bet in migrating the script is splitting it into two separate scripts which communicate with each other. One script which handles the interaction with picamera & gpio and another one soley for user interaction via telegram.
For example, the command to request a picture of the actual mailbox contents is received by the telegram_script. The telegram_script should then tell the low_level_script to execute the capture() function and wait for the return/result of this function (to make sure the picture is saved/updated before the telegram_script tries to send it).
My question is, how do I communicate between the two?
What is the best/easiest way in python to execute a function in the low_level_script with the result returned to the telegram_script?
I think it depends on how you want to structure your system. If you have one script that runs on 2 process using the multiprocessing you could a pipe or a queue to communicate between them.
If you have two very independent scripts, maybe you can look then at using a socket with a Unix socket name.

Looking for a way to check for unexpected windows during a for loop in python automated testing

I am running some automated tests on an POS application where a large number of sales are entered using a for loop. During the test there are times where it is possible for the application window to lose focus, and when this happened we get a pop up window and this causes the test to stop.
I currently have a lot of checks in the code to look for this window after multiple steps in the loop, but each one I add adds time to the sale and slows the test down. Is there a way in python to constantly check for something like these windows.
To note I am using TestComplete and I have looked into the event handlers and it does not appear I will be able to use them due to how the application was developed.
I recommend you try to use an interrupt schedule. The basic idea is that you trigger a function (in this case your function checking for unexpected windows) whenever some counter reaches a value.
If you don't need to check at very specific and short time intervals it is enough to use something like time.clock(). I you DO need the abovementioned there are libraries for that, specifically the signal module or the more advanced sched, which are both part of the standard library (as far as I know, Documentation of signal, Documentation of sched).
There are also other (external, non-standard) modules that can work, but sched and/or signal should be enough here.
Feel free to ask if any further question should arise.
This SO post might also help: real time interrupts in python

How to run a Python script online every N minutes?

To work a bit on my Python, I decided to try to code a simple script for my private use which monitors sites with offers and sends you an email whenever a new offer which you are interested in pops out. I guess I could handle the coding part (extracting the newest one from HTML and such) but I've never really run online any script which requires being fired every N minutes or so. What kind of hosting/server do I need to make my script run independently of my computer and refresh every, say, 5 minutes sending me an email when there's an update?
If you have shell access, you an use crontab to schedule a recurring job.
Otherwise you can use a service like SetCronJob or EasyCron or similar to invoke a script regularly.
Some hosters also provide similar functionalities in their administration interface...

Detecting computer/program shutdown in Python?

I have a Python script that runs in a loop regularly making adjustments to my lighting system. When I shut down my computer, I'd like my script to detect that, and turn off the lights altogether.
How do I detect my computer beginning to shut down in Python?
Or, assuming Windows sends Python a "time to shut down" notice, how do I intercept that to kill my lights and exit the loop?
This is the wrong way to go about performing action at system shutdown time. The job of the shutdown process is to stop running processes and then switch off power; if you try to detect this happening from within your program and react by getting some last action in, it's a race between the OS and your program who gets to go first. More likely than not your program will have been stopped before it managed to perform the necessary action.
Instead, you should hook into the normal protocol for doing things at shutdown. This will tell the shutdown utility to send an explicit signal to your program and wait for it to be acknowledged, which gives you enough time (within reason) to do what you have to do. How exactly to register to be notified varies with the OS, so this is more of an OS-specific question rather than a Python question.
You should react to the WM_ENDSESSION message.
This message is sent when the user logs off or the computer gets shut down.
If you want to react to Sleep/Hibernate as well, you'll need to handle WM_POWERBROADCAST with PBT_APMSUSPEND.
But I don't know how to do that in python. I guess it depends on your windowing framework since you need have a windows/a message loop to receive messages.

How to sleep a python script running as a cronjob?

I wrote a python script to monitor a log file on a CentOS server for a specific value and send an email when it finds it. It runs as a cron every 5 minutes.
My question is what is the best way to put this script to sleep after it has sent the first email. I don't want it to be sending emails every 5 mins, but it needs to wake up and check the log again after an hour or so. This is assuming the problem can be fixed in under an hour. The people who are receiving the email don't have shell access to disable the cron.
I thought about sleep but I'm not sure if cron will try to run the script again if another process is active (sleeping).
cron will absolutely run the script again. You need to think this through a little more carefully than just "sleep" and "email every 10 minutes."
You need to write out your use cases.
System sends message and user does something.
System sends message and user does nothing. Why email the user again? What does 2 emails do that 1 email didn't do? Perhaps you should SMS or email someone else.
How does the user register that something was done? How will they cancel or stop this cycle of messages?
What if something is found in the log, an email is sent and then (before the sleep finishes) the thing is found again in the log. Is that a second email? It is two incidents. Or is that one email with two incidents?
#Lennart, #S. Lott: I think the question was somewhat the other way around - the script runs as a cron job every five minutes, but after sending an error-email it shouldn't send another for at least an hour (even if the error state persists).
The obvious answer, I think, is to save a self-log - for each problem detected, an id and a timestamp for the last time an email was sent. When a problem is detected, check the self-log; if the last email for this problem-id was less than an hour ago, don't send the email. Then your program can exit normally until called again by cron.
When your scripts sends email, make it also create a txt file "email_sent.txt". Then make it check for existence of this txt file before sending email. If it exists, don't send email. If it does not exist, send email and create the text file.
The text files serves as an indicator that email has already been sent and it does not need to be sent again.
You are running it every five minutes. Why would you sleep it? Just exit. If you want to make sure it doesn't send email every five minutes, then make the program only send an email if there is anything to send.
If you sleep it for an hour, and run it every five minutes, after an hour you'll have 12 copies running (and twelve emails sent) so that's clearly not the way to go forward. :-)
Another way to go about this might be to run your script as a daemon and, instead of having cron run it every five minutes, put your logic in a loop. Something like this...
while True:
# The check_my_logfile() looks for what you want.
# If it finds what you're looking for, it sends
# an email and returns True.
if check_my_logfile():
# Then you can sleep for 10 minutes.
time.sleep(600)
# Otherwise, you can sleep for 5 minutes.
else:
time.sleep(300)
Since you are monitoring a log file, It might be worth checking into things that already do log file monitoring. Logwatch is one, but there are log analyzing tools, that handle all of these things for you:
http://chuvakin.blogspot.com/2010/09/on-free-log-management-tools.html
Is a good wrap-up of some options. They would handle yelling at people. Also there are system monitoring tools such as opennms or nagios, etc. They also do these things.
I agree with what other people have said above, basically cron ALWAYS runs the job at the specified time, there is a tool called at which lets you run jobs in the future, so you could batch a job for 5 minutes, and then at runtime decide, when do I need to run again, and submit a job to at for whatever time you need it to run again (be it 5 minutes, 10 minutes or an hour). You'd still need to keep state somewhere (like what #infrared said) that would figure out what got sent when, and if you should care some more.
I'd still suggest using a system monitoring tool, which would easily grow and scale and handles people being able to say 'I'm working on XX NOW stop yelling at me' for instance.
Good luck!

Categories