Getting value using pywinauto from text field - python-2.7

How to get result from ms calculator text field, which displays result of any math operations?
Swapy (v.0.4.3) shows me that this text field has value of 'Static2', after running so simple script i get empty list. Here my code:
from pywinauto import *
n=[]
app=Application()
app.start_("calc.exe")
app.calc.Button11.ClickInput()
app.calc.Button20.ClickInput()
app.calc.Button11.ClickInput()
app.calc.Button21.ClickInput()
n=app.calc.Static2.Texts()#here i expected to get the number
print n
Where i did wrong?

Try
text = app.calc.Static3.window_text()
As I can see in Spy++, Notepad.exe (Win7 version) has 4 static boxes. The third one has non-empty text.
So you need to identify it by "Static3" name, because "Static1" and "Static0" identifies the same static box (that's a bit strange, yes - it's pywinauto feature).
For more detailed investigation use
app.calc.print_control_identifiers() # or .dump_tree()

I may be late to the party but I'm sure this will be handy, Lets say your control textbox is of edit type then you can easily do....
text = app.calc.Static3.get_value()
This is available in - pywinauto 0.6.8

Related

Google Cloud Natural Language API - Sentence Extraction ( Python 2.7)

I am working with the Google Cloud Natural Language API . My goal is to extract the sentences and sentiment inside a larger block of text and run sentiment analysis on them.
I am getting the following "unexpected indent" error. Based on my research, its doesn't appear to be a "basic" indent error (such as an rogue space etc.).
print('Sentence {} has a sentiment score of {}'.format(index,sentence_sentiment)
IndentationError:unexpected indent
the following line of code inside the for loop (see full code below) is causing the problem. If I remove it the issue goes away.
print(sentence.content)
Also if I move this print statement outside the loop, I don't get an error, but only the last sentence of the large block of text is printed (as could be expected).
I am totally new to programming - so if someone can explain what I am doing wrong in very simple terms and point me in the right direction I would be really appreciative.
Full script below
Mike
from google.cloud import language
text = 'Terrible, Terrible service. I cant believe how bad this was.'
client = language.Client()
document = client.document_from_text(text)
sent_analysis = document.analyze_sentiment()
sentiment = sent_analysis.sentiment
annotations = document.annotate_text(include_sentiment=True, include_syntax=True, include_entities=True)
print ('this is the full text to be analysed:')
print(text)
print('Here is the sentiment score and magnitude for the full text')
print(sentiment.score, sentiment.magnitude)
#now for the individual sentence analyses
for index, sentence in enumerate(annotations.sentences):
sentence_sentiment = sentence.sentiment.score
print(sentence.content)
print('Sentence {} has a sentiment score of {}'.format(index, sentence_sentiment))
This looks completely correct, though there may be a tab/space issue lurking there that did not survive being posted in your question. Can you get your text editor to display whitespace characters? There is usually an option to that. If it is a Python-aware editor, there will be a option to change tabs to spaces.
You may be able to make the problem go away by deleting the line
print(sentence.content)
and changing the following one to
print('{}\nSentence {} has a sentiment score of {}'.format(sentence.content, index, sentence_sentiment))

How to set the alignment, or how to find PyGObject documentation

I am trying to right-align some text content in a CellRenderer. Through several searches I found two approaches, but these do not work. With bold-setting, you need to enable this feature first, so I am guessing I also need to enable alignment setting, but have not found how to do this. This runs without exception:
r = Gtk.CellRendererText()
r.props.width_chars = 10
r.set_property('alignment', Pango.Alignment.RIGHT) # no effect
r.props.alignment = Pango.Alignment.RIGHT # no effect
r.props.weight_set = True # not really needed
r.props.weight = Pango.Weight.BOLD # works, output is bold
This is what I guessed from the bold example but does NOT work:
r.props.alignment_set = True
The error is: 'gi._gobject.GProps' object has no attribute 'alignment_set'
Looking at these references I do not find something on GProps:
GObject Ref Manual
Gtk3 Ref Manual
This resource does say something about alignment, but it is unclear to me how to convert this C code to Python/GObject:
Gnome Gtk3 Manual for C
My question is how to fix this problem, where is the ref manual for this PyGObject error message, or how should I code the right-alignment?
Update:
I am currently looking at this similar SO question for clues.
As for the comment of TingPing, I looked at the set_alignment() method,and tried these:
r.set_alignment(Pango.Alignment.RIGHT) # error: set_alignment() takes exactly 3 arguments (2 given)
r.set_alignment(200, 0) # no error, no effect
besides this method seems intended to create some pixels padding at the left, which is not what I need: align text to the right of the cell space.
Update:
Perhaps the above code is good, but perhaps the CellRenderer() has no intrinsic width, no excess space to put to the left of the content. I thought of this because of thinking of simply left-padding my numberic cell content with spaces. Then I need to decide on the maximum field length. Perhaps the CellRenderer does not 'know' about a default field length. I added a settinge to .props.width_chars, but this did unfortunately not cause any rignt-alignment.
Through this C example I tried this to right-align:
r.props.xalign = 1.0
and it works! The xalign is the fraction of free space 0..1.0 to put to the left of the text. The value 0.5 will center the text.

Formatting text in R Shiny

I am developing an application in R Shiny. One of my modules in the application, displays dynamic text depending on user inputs. I would like to display the text as bullet points and additionally would like the text in "strong" or "heading" format. I can do this individually but somehow I am not able to figure out how to combine the 2. So assuming that my function returns a character vector a, with 2 components that I need to display, I can do the following:
HTML("<ul><li>",a[1],"</li><li>",a[2]) #To generate bullet points
HTML(paste(h4(a[1],a[2],sep=''))) #To concatenate and change format to heading
Now my question is - How can I do both (display as bullets with heading format)? I tried different combinations but it's not working.
Secondly, how do I change the colour of my text?
Any help will be greatly appreciated.
Thanks!
To get a bullet list with heading format, you can just add an <h4> tag to the paste. Also, make sure you close all the tags you open, for ex:
HTML("<ul'><li><h4>",a[1],"</h4></li><li><h4>",a[2],"</h4></li></ul>")
You can use inline CSS to change the color, for ex:
HTML("<ul style='color:red'><li><h4>",a[1],"</h4></li><li><h4>",a[2],"</h4></li></ul>")
More info here.

Xlrd list index out of range

I'm just starting to explore Xlrd, and to be honest am pretty new to programming altogether, and have been working through some of their simple examples, and can't get this simple code to work:
import xlrd
book=open_workbook('C:\\Users\\M\\Documents\\trial.xlsx')
sheet=book.sheet_by_index(1)
cell=sheet.cell(0,0)
print cell
I get an error: list index out of range (referring to the 2nd to last bit of code)
I cut and pasted most of the code from the pdf...any help?
You say:
I get an error: list index out of range (referring to the 2nd to last
bit of code)
I doubt it. How many sheets are there in the file? I suspect that there is only one sheet. Indexing in Python starts from 0, not 1. Please edit your question to show the full traceback and the full error message. I suspect that it will show that the IndexError occurs in the 3rd-last line:
sheet=book.sheet_by_index(1)
I would play around with it in the console.
Execute each statement one at a time and then view the result of each. The sheet indexes count from 0, so if you only have one worksheet then you're asking for the second one, and that will give you a list index out of range error.
Another thing that you might be missing is that not all cells exist if they don't have data in them. Some do, but some don't. Basically, the cells that exist from xlrd's standpoint are the ones in the matrix nrows x ncols.
Another thing is that if you actually want the values out of the cells, use the cell_value method. That will return you either a string or a float.
Side note, you could write your path like so: 'C:/Users/M/Documents/trial.xlsx'. Python will handle the / vs \ on the backend perfectly and you won't have to screw around with escape characters.

How to iterate over all the page breaks in an Excel 2003 worksheet via COM

I've been trying to retrieve the locations of all the page breaks on a given Excel 2003 worksheet over COM. Here's an example of the kind of thing I'm trying to do:
Excel::HPageBreaksPtr pHPageBreaks = pSheet->GetHPageBreaks();
long count = pHPageBreaks->Count;
for (long i=0; i < count; ++i)
{
Excel::HPageBreakPtr pHPageBreak = pHPageBreaks->GetItem(i+1);
Excel::RangePtr pLocation = pHPageBreak->GetLocation();
printf("Page break at row %d\n", pLocation->Row);
pLocation.Release();
pHPageBreak.Release();
}
pHPageBreaks.Release();
I expect this to print out the row numbers of each of the horizontal page breaks in pSheet. The problem I'm having is that although count correctly indicates the number of page breaks in the worksheet, I can only ever seem to retrieve the first one. On the second run through the loop, calling pHPageBreaks->GetItem(i) throws an exception, with error number 0x8002000b, "invalid index".
Attempting to use pHPageBreaks->Get_NewEnum() to get an enumerator to iterate over the collection also fails with the same error, immediately on the call to Get_NewEnum().
I've looked around for a solution, and the closest thing I've found so far is http://support.microsoft.com/kb/210663/en-us. I have tried activating various cells beyond the page breaks, including the cells just beyond the range to be printed, as well as the lower-right cell (IV65536), but it didn't help.
If somebody can tell me how to get Excel to return the locations of all of the page breaks in a sheet, that would be awesome!
Thank you.
#Joel: Yes, I have tried displaying the user interface, and then setting ScreenUpdating to true - it produced the same results. Also, I have since tried combinations of setting pSheet->PrintArea to the entire worksheet and/or calling pSheet->ResetAllPageBreaks() before my call to get the HPageBreaks collection, which didn't help either.
#Joel: I've used pSheet->UsedRange to determine the row to scroll past, and Excel does scroll past all the horizontal breaks, but I'm still having the same issue when I try to access the second one. Unfortunately, switching to Excel 2007 did not help either.
Experimenting with Excel 2007 from Visual Basic, I discovered that the page break isn't known unless it has been displayed on the screen at least once.
The best workaround I could find was to page down, from the top of the sheet to the last row containing data. Then you can enumerate all the page breaks.
Here's the VBA code... let me know if you have any problem converting this to COM:
Range("A1").Select
numRows = Range("A1").End(xlDown).Row
While ActiveWindow.ScrollRow < numRows
ActiveWindow.LargeScroll Down:=1
Wend
For Each x In ActiveSheet.HPageBreaks
Debug.Print x.Location.Row
Next
This code made one simplifying assumption:
I used the .End(xlDown) method to figure out how far the data goes... this assumes that you have continuous data from A1 down to the bottom of the sheet. If you don't, you need to use some other method to figure out how far to keep scrolling.
Did you set ScreenUpdating to True, as mentioned in the KB article?
You may want to actually toggle it to True to force a screen repaint. It sounds like the calculation of page breaks is a side-effect of actually rendering the page, rather than something Excel does on demand, so you have to trigger a page rendering on the screen.