Recently I use AppKit to write a program which aims to automatically click inside an application window. When I want to activate the window first, I go through the NSRunningApplication documentation, and found a function called "activateWithOptions", and I wrote a simple program like the following.
Apps = NSWorkspace.sharedWorkspace().runningApplications()
for app in Apps:
print(app.localizedName())
app.activateWithOptions(NSApplicationActivateAllWindows)
Here are my questions.
The first question is that, inside the documentation, the localizedName attribute is a variable, but in Python, you must use it as a function such that you can get the name. Why is the difference?
If you run the program, it just throws an error in the following. But if you changed it to app.activateWithOptions_(NSApplicationActivateAllWindows), the code can be passed. Why is the documentation inconsistent with my usage?
AttributeError: 'NSRunningApplication' object has no attribute 'activateWithOptions'
Localized name
It's not a variable, it's a property declared as:
#property(readonly, copy) NSString *localizedName;
It's synthesized into the _localizedName instance variable and this function:
- (NSString *)localizedName {
return _localizedName;
}
Underscore
PyObjC documentation - Underscores, and lots of them:
An Objective-C message looks like this:
[someObject doSomething:arg1 withSomethingElse:arg2];
The selector (message name) for the above snippet is this (note the colons):
doSomething:withSomethingElse:
In order to have a lossless and unambiguous translation between Objective-C messages and Python methods, the Python method name equivalent is simply the selector with colons replaced by underscores. Since each colon in an Objective-C selector is a placeholder for an argument, the number of underscores in the PyObjC-ified method name is the number of arguments that should be given.
The PyObjC translation of the above selector is (note the underscores):
doSomething_withSomethingElse_
activateWithOptions: -> activateWithOptions_
Related
I am developing a desktop application using pyside(qt), I want to access(iterate) all line edit components of QWidget. In qt I found two methods findChild and findChildren but there is no proper example found and My code shows error, 'form' object has no attribute 'findChild'.
Here 'form' is Qwidget form consist components lineEdit, comboboxes, Qpushbuttons etc.
Code:
lineEdits = form.findChild<QLineEdit>() //This is not working
lineEdits = form.findChild('QLineEdit) //This also not working
The signatures of findChild and findChildren are different in PySide/PyQt4 because there is no real equivalent to the C++ cast syntax in Python.
Instead, you have to pass a type (or tuple of types) as the first argument, and an optional string as the second argument (for matching the objectName).
So your example should look something like this:
lineEdits = form.findChildren(QtGui.QLineEdit)
Note that findChild and findChildren are methods of QObject - so if your form does not have them, it cannot be a QWidget (because all widgets inherit QObject).
Use this method QObject::findChildren(onst QString & name = QString()) with no parameters.
Omitting the name argument causes all object names to be matched.
Here is C++ example code:
QList<QLineEdit*> line_edits = form.findChildren<QLineEdit*>();
I am using PyObj-C and am making some methods in a python file to read and write files using NSDocument, which uses the abstract NSFileCoordinater class. Accessing files this way instead of just using python's open let's these classes handle things for me such as preventing files from being edited from more than one program at a time or giving enough time for read/write operations to finish before it could get deadlocked.
These features are very important, and the app I ma building I want to be up to standard as much as I can here.
I have this code that instantiates a NSDocument object that contains the content of whatever file path you put into it, as a function:
#classmethod
def write(cls, file: str):
path = NSURL.fileURLWithPath_(file)
ext = file.split('.')[-1]
doc = NSDocument.alloc().initWithContentsOfURL_ofType_error_(path, ext, None)
When I call this function with a valid file path I get this error:
File "/Users/user123/PycharmProjects/shoutout/src/sutils/cfiles.py", line 27, in write
doc = NSDocument.alloc().initWithContentsOfURL_ofType_error_(path, ext, None)
objc.error: NSInternalInconsistencyException - readFromData:ofType:error: is a subclass responsibility but has not been overridden.
I have tried to find forums both objective-c, swift, or pyobj-c based as it were asking any keywords such as objective-c is a subclass responsibility but has not been overridden on google, and checked stackoverflow, and github for existing posts on this error but I could find none.
As I understand it Objective-C being polymorphic, has my method initWithContentsOfURL:ofType:error: call readFromData:ofType:error, among other ones at the same time. I don't understand exactly however what it means when it's saying that "is a subclass responsibility but has not been overridden." I am not sure also about what it means to override a class or a one being a responsibility so that doesn't help on my part.
A NSInternalInconsistencyException means a "when an internal assertion fails and implies an unexpected condition within the called code." Not sure what a internal "assertion" is either or what this could mean.
Any idea of what I could do to fix this?
NSDocument is an abstract class that requires you to subclass and implement a number of methods to make it usable. This is document in Apple's documentation for the class.
the older Document-Baed App Programming Guide for Mac gives more information on this.
I am using pywin32 to automate some tasks in software that has an Automation Server technology interface (formerly OLE Automation Server).
This software comes with a somewhat detailed manual with code examples in VBA, C++ or Matlab but no Python. I have built a Python library that can do most of the functionalities built into the software but there are some parts I cannot do in Python.
I cannot change the value of a property if this property is contained in a iterable COM object.
What I can do:
[Documentation for Visibility property]
import win32com.client
app = win32com.client.Dispatch('NAME_OF_APP')
app.Visibility = True
As an example, with this code, I can change the visibility parameter of the software: if it runs with or without GUI.
What I cannot do:
[Documentation for getting and setting current device]
import win32com.client
app = win32com.client.Dispatch('NAME_OF_APP')
app.CurrentDevice(0) = 'NAME OF DEVICE'
I then get the following error:
SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
This error makes sense to me but I cannot find a way to set any of these software properties when they come in the form of an iterable object. As soon as I have to specify an index, I don't know how to set the value.
From what I understand, in C++ we are able to change the value because of pointers but how can we achieve the same thing in Python? Is it possible or do I have to use some C++ code in parallel to my Python to run my library? I don't know anything in C++ so if I could avoid doing that, it would be good.
What I have tried
Of course, the 1st thing I tried was to change () to [] or {} which logically didn't work.
Then I used the Evaluate function in PyCharms to see what was hiding behind my app.CurrentDevice. I was hoping to find sub-attributes that I could then set but I don't see anything inside the object:
[Result of Evaluate on the CurrentDevice object]
Finally, I have tried the following:
import win32com.client
app = win32com.client.Dispatch('NAME_OF_APP')
curr_device = app.CurrentDevice(0)
curr_device = 'NAME OF DEVICE'
I wanted to affect the object to a variable and then change the value but of course, this only rewrites the variable curr-device with 'NAME OF DEVICE' but loses any link to COM Object.
I feel like my questions are similar to the following unanswered question:
How can I set the value of an indexed property of a COM object in Python?
It looks as if win32com is struggling to set the property if there is an additional argument to the put function, which is a little surprising.
First thing to do is to use
app = win32com.client.gencache.EnsureDispatch('NAME_OF_APP')
This creates a Python wrapper for the COM object (rather than just firing function calls at the object and hoping). This may in itself clear up your issue.
If not, here is a quite ugly way of working around. As you have identified, the relevant part of the type library is:
[id(0x00000018),propput, helpstring("property CurrentDevice")]
HRESULT CurrentDevice([in] long lAcq, [in] VARIANT pVal);
And you can use this to set the property at a low level.
win32com dispatch objects are a wrapper for the PyIDispatch object. All dispatch objects support the Invoke method, and you can use this to call the function yourself. NB. Since I don't have access to your COM object, I can't test, so this answer may need some tweaking (!).
The PyIDispatch documentation
Try:
import win32com.client as wc
import pythoncom
app = wc.gencache.EnsureDispatch('NAME OF APP')
app.Visibility=TRUE
newVal = wc.VARIANT(pythoncom.VT_VARIANT,'NAME OF DEVICE')
app._oleobj_.Invoke(24,0,pythoncom.INVOKE_PROPERTYPUT,0,0,newVal)
There are a lot of 'magic' numbers here, but basically:
24 = 0x00000018 in decimal: this is the Id of the property
0 = the LCID, the Locale Id ... I always set it to 0
pythoncom.INVOKE_PROPERTYPUT = the type of call.
0 = whether you care about the return type (you probably don't = False)
0 = first parameter, lAcq, as in CurrentDevice(0)
newVal = second paramter,pVal, the new device name as a VARIANT
I haven't tried this, but pythoncom is pretty good about converting VARIANT types, so you might not need the VARIANT creation, and can just use NAME OF DEVICE directly as the parameter.
My target is to allow an easy way to “filter” previously defined nodes. Consider this fictional YAML file:
%YAML 1.1
---
- fruit: &fruitref { type: banana, color: yellow }
- another_fruit: !rotten *fruitref
What do I need to define in either the YAML file or the Python code that parses this file in order to call a custom function with *fruitref (i.e. the previously defined object, in this case a map) as argument and get the return value? The target is as simple and terse a syntax for “filtering” a previously defined value (map, sequence, whatever).
Note
It seems to me that the construct !tag *alias is invalid YAML, because of the error:
expected <block end>, but found '<alias>'
in "/tmp/test.yaml", line 4, column 21
which most possibly implies that I won't be able to achieve the required syntax, but I do care about terseness (or rather, the target users will).
Routes taken
YAML: !!python/object/apply:__main__.rotten [*fruitref]
It works but it is too verbose for the intended use; and there is no need for multiple arguments, the use case is ALWAYS a filter for an alias (a previously defined map/sequence/object).
YAML: %TAG !f! !!python/object/apply:__main__.
Perhaps !f!rotten [*fruitref] would be acceptable, but I can't find how to make use of the %TAG directive.
EDIT: I discovered that the !! doesn't work for PyYAML 3.10, it has to be the complete URL like this: %TAG !f! %TAG !f! tag:yaml.org,2002:python/object/apply:__main__.
Python: yaml.add_constructor
I already use add_constructor for “casting” maps to specific instances of my classes; the caveat is that tag alias seems to be invalid YAML.
Best so far
add_constructor('!rotten', filter_rotten) in Python and !rotten [*fruitref] in YAML seem to work, but I'm wondering how to omit the square brackets if possible.
It seems that it is not possible to apply a tag to an already tagged reference, so:
!tag *reference
is not acceptable. The best possible solution is to enclose the reference to square brackets (create a sequence) and make the tag to be either a function call or a special constructor expecting a sequence of one object, so the tersest syntax available is:
!prefix!suffix [*reference]
or
!tag [*reference]
I'm currently moving a project from Pylons 1.0 to Pyramid.
My problem so far is how to use restful routes in Pyramid. I'm currently using pyramid_handlers since it seemed like a good start. I'm using Akhet.
So here is the two important lines in my route:
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts")
# or
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts", action="new")
My action:
#action(name="new_account", renderer='accounts/new.mako', request_method='GET')
The errors:
TypeError: 'Accounts' object is not callable
or
ValueError: Could not convert view return value "{}" into a response Object.
Accounts... so far so good, it is easy to understand that pyramid_handlers doesn't seem to register normally or handle name as it should... that said in request.matched_route, I do have "new_account".
If I add "action='new'" in the route definition, it will find the function but it will not listen to the action definition. In other words, it will fail to find a renderer and expect a response object. The request_method parameter doesn't actually do anything yet, so removing it doesn't change any results.
In short, the #action(name="..." doesn't work. Pyramid fails to find the function by itself and if the function name is defined it fails to execute the action statement.
No idea what I'm doing wrong.
Correct way to do it.
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts", action="new_account")
EDIT
route_name is probably going to get used by url generator functions. While action is the actual name in #action. As I understood, #action name was the route_name and not the action name. That makes more sense now.
Well a call to add_handler needs an action pattern. So that's either adding {action} to the url pattern, or setting action= as an argument. Those actions must match the names defined in #action decorators. In your example, you named the action new_account, yet you called add_handler with an action of new. Thus they aren't properly connected.