I want to control python IDLE with pywinauto.
I can start IDLE but cannot input text.
Here is my code:
import pywinauto
app = pywinauto.application.Application(backend="uia").start(r"C:\Python37\pythonw.exe C:\Python37\Lib\idlelib\idle.pyw")
app2 = pywinauto.application.Application().connect(process=app.process)
I tried to use app2.Property.print_control_identifiers() but it returns:
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 256, in __resolve_control
criteria)
File "C:\Python37\lib\site-packages\pywinauto\timings.py", line 458, in wait_until_passes
raise err
pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
app2.Property.print_control_identifiers()
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 595, in print_control_identifiers
this_ctrl = self.__resolve_control(self.criteria)[-1]
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 259, in __resolve_control
raise e.original_exception
File "C:\Python37\lib\site-packages\pywinauto\timings.py", line 436, in wait_until_passes
func_val = func(*args, **kwargs)
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 201, in __get_ctrl
dialog = self.backend.generic_wrapper_class(findwindows.find_element(**criteria[0]))
File "C:\Python37\lib\site-packages\pywinauto\findwindows.py", line 84, in find_element
elements = find_elements(**kwargs)
File "C:\Python37\lib\site-packages\pywinauto\findwindows.py", line 303, in find_elements
elements = findbestmatch.find_best_control_matches(best_match, wrapped_elems)
File "C:\Python37\lib\site-packages\pywinauto\findbestmatch.py", line 533, in find_best_control_matches
raise MatchError(items = name_control_map.keys(), tofind = search_text)
pywinauto.findbestmatch.MatchError: Could not find 'Property' in 'dict_keys(['*Python 3.7.2 Shell*TkTopLevel', '*Python 3.7.2 Shell*', 'TkTopLevel'])'
How to solve the problem?
Thank you.
app = pywinauto.application.Application(backend="uia").start(r"C:\Python37\pythonw.exe C:\Python37\Lib\idlelib\idle.pyw")
app2 = pywinauto.application.Application().connect(process=app.process)
app3 = app2.top_window()
app3.print_control_identifiers()
I doubt that you can do whatever it is that you are trying to do. The pywinauto site says "pywinauto is a set of python modules to automate the Microsoft Windows GUI. At its simplest it allows you to send mouse and keyboard actions to windows dialogs and controls." IDLE uses tkinter, which uses the tcl/tk gui framework. While that ultimately uses Windows graphics, it may not be at the level that pywinauto accesses.
You can use pyautogui which is best for windows GUI automation
I converted RDP connection to automation using pyautogui
import pyautogui
import time
import os
os.system("C:\\Users\Administrator\\Desktop\\RDC.bat")
print(pyautogui.position())
time.sleep(5)
pyautogui.click(490,404)
pyautogui.typewrite("Bitwise$123")
pyautogui.typewrite(["Enter"])
Related
I have a script, which has been working fine in April 2021 when I created it, but now it gives me the following error. I'm not very experienced in coding, so if anyone can help me it would be great.
What I'm trying to do is simply download a song from youtube as a mp4. I can see that the error says there is something wrong with the pytube module imported, but I am not skilled enough to see what it is.
I'm using MacOS 12.1, Pycharm 2020.3, and Python 3.9.
Script:
import pytube
url = str('https://www.youtube.com/watch?v=gJLIiF15wjQ')
youtube = pytube.YouTube(url)
video = youtube.streams.get_by_itag(140)
video.download(output_path='/Users/clarajacobsen/Documents/TrueFIR/Klub100/Songs/', filename='test')
Error:
Traceback (most recent call last):
File "/Users/user/Documents/Folder1/venv/test.py", line 8, in <module>
video = youtube.streams.get_by_itag(140)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/__main__.py", line 292, in streams
return StreamQuery(self.fmt_streams)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/__main__.py", line 177, in fmt_streams
extract.apply_signature(stream_manifest, self.vid_info, self.js)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/extract.py", line 409, in apply_signature
cipher = Cipher(js=js)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/cipher.py", line 43, in __init__
self.throttling_plan = get_throttling_plan(js)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/cipher.py", line 387, in get_throttling_plan
raw_code = get_throttling_function_code(js)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/cipher.py", line 301, in get_throttling_function_code
code_lines_list = find_object_from_startpoint(js, match.span()[1]).split('\n')
AttributeError: 'NoneType' object has no attribute 'span'
After trying out solution 1, suggested by Sarim, error in PyCharm:
Traceback (most recent call last):
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/__main__.py", line 177, in fmt_streams
extract.apply_signature(stream_manifest, self.vid_info, self.js)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/extract.py", line 409, in apply_signature
cipher = Cipher(js=js)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/cipher.py", line 29, in __init__
self.transform_plan: List[str] = get_transform_plan(js)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/cipher.py", line 197, in get_transform_plan
return regex_search(pattern, js, group=1).split(";")
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/helpers.py", line 129, in regex_search
raise RegexMatchError(caller="regex_search", pattern=pattern)
pytube.exceptions.RegexMatchError: regex_search: could not find match for iha=function\(\w\){[a-z=\.\(\"\)]*;(.*);(?:.+)}
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/user/Documents/Folder1/venv/test.py", line 5, in <module>
video = youtube.streams.get_by_itag(140)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/__main__.py", line 292, in streams
return StreamQuery(self.fmt_streams)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/__main__.py", line 184, in fmt_streams
extract.apply_signature(stream_manifest, self.vid_info, self.js)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/extract.py", line 409, in apply_signature
cipher = Cipher(js=js)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/cipher.py", line 29, in __init__
self.transform_plan: List[str] = get_transform_plan(js)
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/cipher.py", line 197, in get_transform_plan
return regex_search(pattern, js, group=1).split(";")
File "/Users/user/Documents/Folder1/venv/lib/python3.9/site-packages/pytube/helpers.py", line 129, in regex_search
raise RegexMatchError(caller="regex_search", pattern=pattern)
pytube.exceptions.RegexMatchError: regex_search: could not find match for iha=function\(\w\){[a-z=\.\(\"\)]*;(.*);(?:.+)}
After trying to run it in Google Colab:
/usr/local/lib/python3.7/dist-packages/pytube/cipher.py in get_throttling_function_code(js)
299
300 # Extract the code within curly braces for the function itself, and merge any split lines
--> 301 code_lines_list = find_object_from_startpoint(js, match.span()[1]).split('\n')
302 joined_lines = "".join(code_lines_list)
303
AttributeError: 'NoneType' object has no attribute 'span'
To fix this issue, This doesnt depends on which operating system you are on or which python you are using. Follow these steps:
I used Colab for this, if you are using Google colab use it and test it.
Install Pytube with !pip install pytube
After installing pytube just shutdown the kernel and the application you are using for it. either VSCode, Jupyter notebook or Colab. shut down its kernel.
Then run the enviroment again and try importing and running your code.
It should run now.
or if it gives you the same error as before:
Go to the files where pytube is install and go to folder in pytube named "pytube" then go into "cipher.py" and open it.
Search for the line: 293. Where name = re.escape(get_throttling_function_name(js))
Replace name = "iha"
Then close all kernels and file you are running the code on. and restart them completely after shutting down.
These two solutions should work 100%. Solution that worked for me is first one.
As the error tells us, you have a NoneType object called youtube in line 8 which was created before in line 7. Did you check if the YouTube link or anything on that video page that concerns you has changed?
I am making a program that will allow my phone to share its clipboard with my PC. I am using Pyperclip as it appears to be the easiest and most cross-platform solution. However, when I run the code below:
...
elif "incoming_clipboard:" in server_command:
print(server_command)
pyperclip.copy(server_command.replace("incoming_clipboard: ", ""))
...
I get the error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
self.run()
File "/usr/lib/python3.9/threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "/home/chris/Documents/Programming/Synchrony/Desktop/Phone.py", line 30, in do_sync
self.handle_commands(bluetooth_socket)
File "/home/chris/Documents/Programming/Synchrony/Desktop/Phone.py", line 65, in handle_commands
pyperclip.copy(server_command.replace("incoming_clipboard: ", ""))
File "/usr/lib/python3.9/site-packages/pyperclip/__init__.py", line 659, in lazy_load_stub_copy
return copy(text)
File "/usr/lib/python3.9/site-packages/pyperclip/__init__.py", line 158, in copy_gtk
cb = gtk.Clipboard()
File "/usr/lib/python3.9/site-packages/gi/__init__.py", line 69, in __getattr__
raise AttributeError(_static_binding_error)
AttributeError: When using gi.repository you must not import static modules like "gobject". Please change all occurrences of "import gobject" to "from gi.repository import GObject". See: https://bugzilla.gnome.org/show_bug.cgi?id=709183
I know its not due to the string being invalid or anything, because 1) I am explicitly converting it from bytes to a string, and 2) it prints perfectly fine. I don't know if this is relevant, but I am using Linux, so perhaps that is affecting Pyperclip?
Do you guys have any solutions?
https://github.com/dynobo/normcap/issues/100
After going to the Github page for PyperClip, I found a similar issue that someone else had that suggested switching to PyClip. After installing PyClip and implementing it in project, I can confirm that it works perfectly without any issues.
After searching I am not able to find a good response:
I am trying to automate company software using pywinauto. I try to use app.print_control_identifiers() wherever possible. And it has been a God send! Thanks to folks on Youtube and Vasily's posts. See code below.
During the install, it wants to install a MS VC++ redistributable and I can handle that.
The next issue is telling me that the version of Adobe Flash Player (I know right?) is incompatible. I have used Inspect to ID the OK button I need to click to move on. Here is the code (cleaned up for public consumption):
from pywinauto.application import Application
import time
app = Application(backend="uia").start("C:\\Users\\me\\program.exe")
time.sleep(5)
#This addresses the need to install Microsoft C++ Redistributable
dlg = app['program - InstallShield Wizard']
dlg.Install.click()
time.sleep(5)
#This is to get past an install failure and to move on
dlg.Yes.click()
time.sleep(10)
#This is a dialog box saying that some component is incompatible and this is where I am stuck
# And the window title now just says 'program' vs. 'program - InstallShield Wizard'
new_dlg = app['program']
new_dlg.OK.click()
Here is the failure info:
C:\Python37\python.exe C:/Users/me/PycharmProjects/myProject/pywinauto_install.py
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 258, in __resolve_control
criteria)
File "C:\Python37\lib\site-packages\pywinauto\timings.py", line 458, in wait_until_passes
raise err
pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/me/PycharmProjects/myProject/pywinauto_install.py", line 23, in <module>
new_dlg.OK.click()
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 379, in __getattribute__
ctrls = self.__resolve_control(self.criteria)
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 261, in __resolve_control
raise e.original_exception
File "C:\Python37\lib\site-packages\pywinauto\timings.py", line 436, in wait_until_passes
func_val = func(*args, **kwargs)
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 203, in __get_ctrl
dialog = self.backend.generic_wrapper_class(findwindows.find_element(**criteria[0]))
File "C:\Python37\lib\site-packages\pywinauto\findwindows.py", line 87, in find_element
raise ElementNotFoundError(kwargs)
pywinauto.findwindows.ElementNotFoundError: {'best_match': 'program', 'backend': 'uia', 'process': 22184}
Process finished with exit code 1
I am creating new_dlg based on an SO post I saw, so if this is wrong, please slap my hand. I am not a trained developer.
Thanks
To check texts of the top level dialog windows print this:
print([w.window_text() for w in app.windows()])
Then just copy the correct one to your code as a dict key instead of app['program']. More flexible way looks so:
new_dlg = app.window(title_re="Program - .*")
I have the virtualbox 5.0.10 Python sdk in my source root, but when I run my code the program will fail:
Traceback (most recent call last):
File "C:/Users/xiao/.PyCharm50/config/scratches/scratch", line 2, in <module>
mgr=vboxapi.VirtualBoxManager()
File "C:\Users\xiao\Desktop\test\vboxapi\__init__.py", line 1018, in __init__
self.platform = PlatformMSCOM(dPlatformParams)
File "C:\Users\xiao\Desktop\test\vboxapi\__init__.py", line 513, in __init__
win32com.client.gencache.EnsureDispatch('VirtualBox.Session')
File "C:\Python27\lib\site-packages\win32com\client\gencache.py", line 540, in EnsureDispatch
disp_class = CLSIDToClass.GetClass(str(disp_clsid))
File "C:\Python27\lib\site-packages\win32com\client\CLSIDToClass.py", line 46, in GetClass
return mapCLSIDToClass[clsid]
KeyError: '{7844AA05-B02E-4CDD-A04F-ADE4A762E6B7}'
Here is my code: (really simple, right?)
import vboxapi
mgr=vboxapi.VirtualBoxManager()
This program is buggy under Python 2.7.6, but runabble under Python 3.4.0.
Why? How can I fix that?
I need to display notifications in MacOS. Simply running the script with python can display notification. But whenever I pack the script using Pyinstaller, I get the following error. Seems like Pyinstaller is having some problem with working on Mac notifications. I also tried using pync (Python binding for terminal notifier). In all cases, simply running the app python notify.py works, but freezing the script using Pyinstaller doesn't seem to work.
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Library/Python/2.7/site-packages/PyInstaller-2.1-py2.7.egg/PyInstaller/loader/pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/Foundation/__init__.py", line 10, in <module>
from CoreFoundation import *
File "/Library/Python/2.7/site-packages/PyInstaller-2.1-py2.7.egg/PyInstaller/loader/pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "/Users/jacob/mac-notify/build/notify/out00-PYZ.pyz/CoreFoundation", line 19, in <module>
File "/Users/jacob/mac-notify/build/notify/out00-PYZ.pyz/objc._bridgesupport", line 121, in initFrameworkWrapper
File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 939, in resource_exists
File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 1392, in has_resource
File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 1447, in _has
NotImplementedError: Can't perform this operation for unregistered loader type
logout
I am using the following Python script to display notification
import Foundation
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
notification = NSUserNotification.alloc().init()
notification.setTitle_("TestTitle")
notification.setInformativeText_("This is sample text")
center = NSUserNotificationCenter.defaultUserNotificationCenter()
center.deliverNotification_(notification)
I had similar problems and this is how I made it work. You need not use Foundation as its making the problem with Pyinstaller (Not sure why this is causing an issue) and is not used elsewhere in your code.
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
notification = NSUserNotification.alloc().init()
notification.setTitle_("TestTitle")
notification.setInformativeText_("This is sample text")
center = NSUserNotificationCenter.defaultUserNotificationCenter()
center.deliverNotification_(notification)
At this point, it may throw some error or the notification just don't show up. Just add CFBundleIdentifier key into the info.plist file generated by pyinstaller.