Change Window upon flashdrive detection Tkinter - python-3.x

So far I have a GUI but right now I'm having a problem on how to change the window upon usb insertion. I tried pyudev for monitoring devices but whenever I add it in my GUI code, it doesn't run even though these codes worked when separated. Also I want to list the files in the GUI so that the user can select which file to print. Thank you in Advance! :)
This is my code for detection of usb devices.
import pyudev
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by(subsystem='usb')
for device in iter(monitor.poll, None):
if device.action == 'add':
print('{} connected'.format(device))
if device.action == 'remove':
print('{} removed' .format(device))

Related

Jetson AGX Orin: tty device usable only once before failing

I am using a barcode scanner as part of a project, everything works correctly until I exit the program then I can't communicate anymore with the barcode scanner. This holds true for whatever program I'm running, be it one of my own or just using screen to monitor the transmissions. As soon as I exit, the only way to make the scanner work again is to unplug and replug.
The scanner (this one) is always mounted correctly (usually at /dev/ttyACM0) and communicates by SSI over USB CDC.
I’ve tried monitoring with pyserial’s miniterm and with screen /dev/ttyACM0 9600 but the same problem arises (f.e. screen just says [screen is terminating])
Mind you, everything works well on another computer so I believe it might be an issue with the Jetson rather than the scanner.
In the project I’m trying to run, I use pyserial to interact with the device. Here is an extract of the code to give you an idea of how I use it:
import serial
serial_port = "/dev/ttyACM0"
baud_rate = 9600
with serial.Serial(serial_port, baud_rate, timeout=0.1) as device_serial:
device_serial.flush()
while True:
try:
# read a line from the serial port
barcode_byte_string = device_serial.readline()
if len(barcode_byte_string) > 0:
# convert the byte string to a string and strip the newline character
barcode = barcode_byte_string.decode("utf-8").rstrip()
# publish the barcode to the topic
self.publish_barcode(barcode, serial_port)
except serial.SerialException as e:
# exit with error code 1. This will cause the application to be restarted.
sys.exit(1)
except Exception as e:
break

Python - Mouse clicks/Keyboard Clicks on window in background

I wanted to create a metin2 bot, nothing complicated. I am new into that so i just started to look for tutorials on youtube to find something that would lead me to world of coding, how does it work, what language is used to write it ect. So I found a tutorial on youtube about open CV Learn Code By Gaming - OpenCV and thought that's awesome thing to start with.
I got to the point where I can easily detect the names of monsters/metins and wont have any problems in finding the right points to click. After detection started working I thought about automating clicking on the window to farm some items etc. Simple things like clicking e.g 50 pixels below the name to auto attack worked just fine but the problem was that I wanted to make more bots to maximalize farming. So when i started to add more clients I got a problem where e.g you have to hold down SPACE in one window to attack from horse and click on another window which was stopping attacking from horse. So I thought about finding some code that can basically send message directly to window without controlling a mouse or keyboard so you can run multiple bots in one time and each will do perfect meanwhile you can do anything else on pc because your mouse and keyboard aren't used.
Let's start from code I found and none worked for windows in background (even with administrator privileges). Pyautogui doesn't work in background (window has to be in foreground to be clicked on and it controls mouse so there is no point in using that.
From that code I learned that I need to find "window ID" to connect to it and send messages. When i print hWnd it shows the numbers in Terminal and code passes without any fails but does nothing except printing the window ID ( Parent Handle ). Ofc I pip installed pywin32
import win32gui
import win32api
import win32con
def click(x, y):
hWnd = win32gui.FindWindow(None, "Client")
print(hWnd)
lParam = win32api.MAKELONG(x, y)
win32api.SendMessage(hWnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
win32api.SendMessage(hWnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, lParam)
click(100, 100)
Than i found another code that looked similar but used different function so first i used
wdname = 'Client'
hwnd = win32gui.FindWindow(None, wdname) # parent handle
print(hwnd)
Which printed me a window ID that i used in parameters in function
def control_click(x, y, handle, button):
l_param = win32api.MAKELONG(x, y)
if button == 'left':
win32gui.PostMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, l_param)
win32gui.PostMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, l_param)
elif button == 'right':
win32gui.PostMessage(handle, win32con.WM_RBUTTONDOWN, 0, l_param)
win32gui.PostMessage(handle, win32con.WM_RBUTTONUP, 0, l_param)
control_click(200, 200, 329570, button ='left')
But it still did nothing but code passed clear
Anyone have any ideas about how to make clicks/keyboard clicks in python on window in background without taking controll of mouse/keyboard? If you have any experience in automating and know better ways to create automation for clicking ect. and want to share it please do. If that can be done in another programming language also share your toughts about that of course if you want to.
Windows 10 x64
Python used: 3.9.2
All codes i found in topics were out of date that s why i am asking for help there. Thanks in advance :)

PYTHON rumps program stops responding after subprocess calls another script

I am currently working on a project that contains many system tray utilities on mac osx, one of these utilities is a 'fake friend soundboard' where I am to enable the user to click on the module then select as example "Discord Ping x1" and the program playback a soundfile of the ping.
Im using RUMPS which enables me to add menus to the system tray however when trying to use libraries to play sounds directly through upon the #rumps.clicked, nothing seems to happen
Instead I've programmed it to run another script that can easily play the sound inside another folder containing all the sounds.
When running the script and clicking a sound, it plays the sound exactly as intended,
but then the program stops responding...
Is this something I'm doing wrong with my code or is there another way i could play the sound using this library?
Heres the code:
import rumps
import subprocess
class sound(rumps.App):
def __init__(self):
super(sound, self).__init__("🔊")
self.menu = ["Fake friend soundboard",
None,
"Discord Sounds:",
"Ping x1",
"Incoming Call",
"Enter Call",
"Leave Call",
"Mute",
"Deafen",
None,
"Skype Sounds:",
"Incoming Call",
None,
"Random:",
"okbuddyretard",
None]
#rumps.clicked("Ping x1")
def about(sender):
subprocess.run("python3 soundboard/discord_pingx1.py", shell=True)
if __name__ == "__main__":
sound().run()
In the soundboard folder there is the sounds folder containing the discord folder containing **
discord_ping.wav
The soundboard folder also hold the discordd_pingx1.py script which is below.
import pyglet
def sound():
sound = pyglet.resource.media('sounds/discord/discord_ping.wav', streaming=False)
sound.play()
pyglet.app.run()
sound()
after running my main.py (opens all the modules)
and clicking the sound tab and then clicking the button set to make the sound,
it plays, but then stops responding.
Any help at all would be much appreciated.
I highly recommend avoiding the insert of subprocess or sys-calls inside of a Python script that executes Objective-C code. This leads to Aborts and Traps. Instead, refer to Apple's APIs and utilize AppleScript (osascript).
Here is a better implementation that calls a script to call your script from osascript:
exec.py
import platform
import subprocess, sys, os
applescript = '''\
do shell script "bash /path/to/file/myShellScript.sh"\
'''
# parse and stdout
args = [item for x in [("-e",l.strip()) for l in applescript.split('\n') if l.strip() != ''] for item in x]
proc = subprocess.Popen(["osascript"] + args ,stdout=subprocess.PIPE )
progname = proc.stdout.read().strip()
sys.stdout.write(str(progname))
The parser takes the string with the osascript in it and parses it for a stdout write. Stdout writes are very safe, considering they are handling data from the same thread.
/path/to/file/myShellScript.sh (add the shebang on line 1 as well)
#!/bin/bash
python3 soundboard/discord_pingx1.py
This 100% handles your problem without causing subprocess errors. If you get hung with subprocess, your computer will continue running Python3. If the Application doesn't stop freezing, exit the app by cmd+Space and typing Activity Monitor. Then, find Python3 by cmd+f and typing python3. Click it and press Quit in the top left corner (the X or stop-light symbol).

Python Multithreading with pynput.keyboard.listener

I am building a self-driving rc car. The car is controlled by a raspberry pi (client) that sends image data to my computer (server) and the computer processes the image frames and responds to the car with what to do (all using python sockets). This works perfectly well. I am now trying to add a key listener to python so I can manually control the car WHILE all of the socket interractions are happening. I would like to use multithreading to do so. Here is how I believe it should work:
import cv2
from pynput import keyboard
from Server import Server
###Keyboard Listener###
def keyPress(key): #send keypress to client
server.sendCommand((str(key)))
with keyboard.Listener(on_press=keyPress) as listener: #new listener thread
listener.join() #activate thread
###Server/ client interaction###
host, port = '10.78.1.195', 8000 # home
server = Server(host, port) #server object
server.connect() #connect
while server.isOpened(): #do while the server is open
frame = server.getStreamImage() #get an image from the client each frame
server.sendCommand("0") #send a command to the server (arbituary for now, but will be a neural network ouotput
cv2.imshow("t", frame) # show image
# cv2.imshow("tttttt", nnInput) # show image CONFIGURE PERSPECTIVE TRANSFORM AFTER CAMERA MOUNT
if cv2.waitKey(1) == ord('q'): #quit if q pressed
server.sendCommand('q') # tell client to close
server.close() # break if 'q' pressed
cv2.destroyAllWindows() #close opencv windows
If you would like any of the client or server code, I would be happy to show it. I didn't inlude it because it's working perfectly.
SO, in my mind, the while loop and the keyboard listener should operate in parallel, and I'm not sure why they are not. With this configuration, the keypresses are tracked, but the server/client interactions never begin. I have tried reformatting the code and I can't seem to get the operations to happen parallel.
If there is a simpler or less resource intensive way to do this, I am open to new ideas. This is just what makes the most sense to me. I really just want the code to be as clean as possible.
My python version is 3.7. I am running Ubuntu 19.10. pynput is version 1.4.5.
If I can provide any additional info, please ask. Thank you very much!
Instead of using the with statement to initialise your listener try:
listener = keyboard.Listener(on_press=keyPress)
listener.start()
The with statement is blocking the main thread.
Using start instead of with / join you create a non-blocking thread allowing the main loop to start.

Why do I get NSAutoreleasePool double release when using Python/Pyglet on OS X

I'm using Python 3.5 and Pyglet 1.2.4 on OS X 10.11.5. I am very new to this setup.
I am trying to see if I can use event handling to capture keystrokes (without echoing them to the screen) and return them to the main program one at a time by separate invocations of the pyglet.app.run method. In other words I am trying to use Piglet event handling as if it were a callable function for this purpose.
Below is my test program. It sets up the Pyglet event mechanism and then calls it four times. It works as desired but causes the system messages shown below.
import pyglet
from pyglet.window import key
event_loop = pyglet.app.EventLoop()
window = pyglet.window.Window(width=400, height=300, caption="TestWindow")
#window.event
def on_draw():
window.clear()
#window.event
def on_key_press(symbol, modifiers):
global key_pressed
if symbol == key.A:
key_pressed = "a"
else:
key_pressed = 'unknown'
pyglet.app.exit()
# Main Program
pyglet.app.run()
print(key_pressed)
pyglet.app.run()
print(key_pressed)
pyglet.app.run()
print(key_pressed)
pyglet.app.run()
print(key_pressed)
print("Quitting NOW!")
Here is the output with blank lines inserted for readability. The first message is different and appears even if I comment out the four calls to piglet.app.run. The double release messages do not occur after every call to event handling and do not appear in a consistent manner from one test run to the next.
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 "/Users/home/PycharmProjects/Test Event Handling/.idea/Test Event Handling 03B.py"
2016-07-28 16:49:59.401 Python[11419:4185158]ApplePersistenceIgnoreState: Existing state will not be touched. New state will be written to /var/folders/8q/bhzsqtz900s742c17gkj_y740000gr/T/org.python.python.savedState
a
2016-07-28 16:50:02.841 Python[11419:4185158] *** -[NSAutoreleasePool drain]: This pool has already been drained, do not release it (double release).
2016-07-28 16:50:03.848 Python[11419:4185158] *** -[NSAutoreleasePool drain]: This pool has already been drained, do not release it (double release).
a
a
2016-07-28 16:50:04.632 Python[11419:4185158] *** -[NSAutoreleasePool drain]: This pool has already been drained, do not release it (double release).
a
Quitting NOW!
Process finished with exit code 0
Basic question: Why is this happening and what can I do about it?
Alternate question: Is there a better way to detect and get a users keystrokes without echoing them to the screen. I will be using Python and Pyglet for graphics so I was trying this using Pyglet's event handling.
Try to play with this simple example. It uses the built-in pyglet event handler to send the key pressed to a function that can then handle it. It shows that pyglet.app itself is the loop. You don't need to create any other.
#!/usr/bin/env python
import pyglet
class Win(pyglet.window.Window):
def __init__(self):
super(Win, self).__init__()
def on_draw(self):
self.clear()
# display your output here....
def on_key_press(self, symbol, modifiers):
if symbol== pyglet.window.key.ESCAPE:
exit(0)
else:
self.do_something(symbol)
# etc....
def do_something(symbol):
print symbol
# here you can test the input and then redraw
window = Win()
pyglet.app.run()

Resources