I've written a script that periodically scrapes twitter data using while True.
For the except element, I initiate a one-time scrape of a large chunk of data.
The only way I can trigger this is by using Ctrl+C. What I want to do is map the 'Ctrl+C' function to the button on my RaspberryPi Pibrella.
I've looked around here, there, and everywhere, but had no joy. The only module I can find does not work on Raspberry Pi (Linux).
def status_update():
while True:
try:
scrape_some_stuff()
time.sleep(1x60)
except:
scrape_lots_of_stuff()
time.sleep(1x60)
pibrella has a package (pip install pibrella) so you can easily monitor the button status, with which you can use to raise your exception
import pibrella
# add this line into your codes
pibrella.button.pressed(raise Exception)
Their github repo has some examples.
Related
I want to make a plugin for neovim using the Python API (pynvim). The problem is I want to get the current buffer's text, updated real time. I have searched on the web and didnt find any useful (or understandable) documentation for this.
You can use pynvim to subscribe to an event in neovim. Do keep in mind that pynvim is async, but my example is using a simple while loop do demonstrate how to monitor for realtime change in a buffer and get its content.
from time import sleep
from pynvim import attach, api
nvim = attach('socket', path='/tmp/nvim')
buffer = nvim.current.buffer
event = api.nvim.Nvim.from_nvim(nvim) # use the loaded nvim session
listen = event.subscribe('TextChangedI') # refer to events https://neovim.io/doc/user/autocmd.html#events
while True:
sleep(2)
print(listen)
# read and print contents of the whole buffer
for line in range(len(buffer)):
print(buffer[line])
I'm currently working on a Selenium program that requires I open up a system file-selector dialog. Unfortunately it's impossible to circumvent this by just sending keys to a webpage attribute, as I have to select a button with no file-acceptance, which automatically opens up the file-selector dialog.
I believe the only solution is to send keys through the system itself to the file selector. Unfortunately, the method I'm currently using (below) requires that the window be active for it to receive the keys.
I used the pynput library in order to send the keys on my first iteration. The pynput documentation for keyboards can be found here:
https://pynput.readthedocs.io/en/latest/keyboard.html
from pynput.keyboard import Key, Controller
import os, time
file = "723583.jpg" #this is a local directory file
keyboard = Controller()
keyboard.type(os.path.abspath(file))
time.sleep(5) #Please ignore the bad style of using these sleeps
keyboard.press(Key.enter) #They're just for testing
time.sleep(3)
keyboard.press(Key.enter)
time.sleep(3)
On other Stackoverflow questions, I've found solutions for Windows computers (e.g. using win32), though I haven't been able to find anything for MacOS, which I'm currently using, or an equivalent multi-platform solution. Does anybody know how I might be able to send keys to a background application as such?
first of all let me tell you I'm kind of a newb at threads and multiprocessing.
I've got a Python graphical program that once you choose a translation site and click a button, calls a thread to open up a browser and do a search on that given site (I'm using splinter, which uses selenium, and qt for the graphical part) of the terms located in a text file selected by the user.
I'm trying to timeout the search of each term on the site to 30 seconds, because sometimes there are loading problems, or other issues, and I want to be able to skip the term if it takes to time to search and try at a later time.
So:
I have this code on the event handler of the button:
self.searchThread = PesquisaThread()
self.searchThread.start()
Then at the run method of the thread I have:
glossary.do_search(0, site_to_look_for)
'glossary' is the class of the gui.
Then if the glossary translib is selected 'do_search' does:
search_translib(language_from,language_to)
Which then calls for the function that does the opening of the browser and clicking of the links, etc, like so...
p = multiprocessing.Process(target=search_term_language,args=(browser,'Portuguese', row, column,termo_unicode))
p.start()
p.join(30)
But when this particular code runs I get:
pickle.PicklingError: Can't pickle '_subprocess_handle' object: <_subprocess_handle object at 0x0230DA60>
I'm at a loss, does anyone know what is going on.
Thank you
Daniel
I was wondering if there was a way of watching for a window to open and when it does close it? I've got a very annoying VPN client on our Mac systems that is very verbose and gets really annoying. There's no configuration to change this, so I'm wondering if I could write a Python script that is always running and watching for the window to open and close it?
As far as I know, there's no global notification that gets generated every time a window is opened, and no standard notification that every app uses, and no other way to do this in general, short of (a) injecting code into the VPN client, (b) using deprecated functionality like CGRemoteOperation, or (c) reverse engineering undocumented Window Server functionality.
So, the simplest solution is to periodically poll for windows and close them, probably using UI scripting via ScriptingBridge, NSAppleScript (through pyobjc), or appscript.
For example:
se = appscript.app('SystemEvents')
while True:
try:
client = se.application_processes['Annoying VPN Client']
window = client.windows['Annoying Window']
close = window.buttons[1]
close.click()
except Exception as e:
print('Exception: {}'.format(e))
time.sleep(1)
If you're interested in the other options—which you won't be able to do from Python—let me know. If you're familiar with system-level C and ObjC programming, creating a SIMBL program that hooks into the ObjC runtime to insert your own delegate in front of the existing one and intercept the relevant messages isn't that hard.
I am running an automated test using an Android emulator driving an app with a Monkey script written in Python.
The script is copying files onto the emulator, clicks buttons in the app and reacts depending on the activities that the software triggers during its operation. The script is supposed to be running the cycle a few thousand times so I have this in a loop to run the adb tool to copy the files, start the activities and see how the software is reacting by calling the getProperty method on the device with the parameter 'am.current.comp.class'.
So here is a very simplified version of my script:
for target in targets:
androidSDK.copyFile(emulatorName, target, '/mnt/sdcard')
# Runs the component
device.startActivity(component='com.myPackage/com.myPackage.myactivity')
while 1:
if device.getProperty('am.current.comp.class') == 'com.myPackage.anotheractivity':
time.sleep(1) # to allow the scree to display the new activity before I click on it
device.touch(100, 100, 'DOWN_AND_UP')
# Log the result of the operation somewhere
break
time.sleep(0.1)
(androidSDK is a small class I've written that wraps some utility functions to copy and delete files using the adb tool).
On occasions the script crashes with one of a number of exceptions, for instance (I am leaving out the full stack trace)
[com.android.chimpchat.adb.AdbChimpDevice]com.android.ddmlib.ShellCommandUnresponsiveException
or
[com.android.chimpchat.adb.AdbChimpDevice] Unable to get variable: am.current.comp.class
[com.android.chimpchat.adb.AdbChimpDevice]java.net.SocketException: Software caused connectionabort: socket write error
I have read that sometimes the socket connection to the device becomes unstable and may need a restart (adb start-server and adb kill-server come in useful).
The problem I'm having is that the tools are throwing Java exceptions (Monkey runs in Jython), but I am not sure how those can be trapped from within my Python script. I would like to be able to determine the exact cause of the failure inside the script and recover the situation so I can carry on with my iterations (re-establish the connection, for instance? Would for instance re-initialising my device with another call to MonkeyRunner.waitForConnection be enough?).
Any ideas?
Many thanks,
Alberto
EDIT. I thought I'd mention that I have discovered that it is possible to catch Java-specific exceptions in a Jython script, should anyone need this:
from java.net import SocketException
...
try:
...
except(SocketException):
...
It is possible to catch Java-specific exceptions in a Jython script:
from java.net import SocketException
...
try:
...
except(SocketException):
...
(Taken from OP's edit to his question)
This worked for me:
device.shell('exit')# Exit the shell