pywinauto batch file running error - python-2.7

Im a biologist and new to pywinauto, i wrote a code to open an input file in HYPHY application using pywinauto, when i run my code line by line in command line it works fine but when i run the code as a batch file it gives the following error.
Traceback (most recent call last):
File "C:\Users\Masyh\Desktop\autowin_test.py", line 8, in <module>
w_handle = pywinauto.findwindows.find_windows(title=u' Please select a batch file to run:', class_name='#32770')[0]
IndexError: list index out of range
the code is:
import pywinauto
pwa_app = pywinauto.application.Application()
w_handle = pywinauto.findwindows.find_windows(title=u'HYPHY Console', class_name='HYPHY')[0]
window = pwa_app.window_(handle=w_handle)
window.SetFocus()
window.MenuItem(u'&File->&Open->Open &Batch File\tCtrl+O').Click()
w_handle = pywinauto.findwindows.find_windows(title=u' Please select a batch file to run:', class_name='#32770')[0]
window = pwa_app.window_(handle=w_handle)
window.SetFocus()
ctrl = window['Edit']
ctrl.Click()
ctrl.TypeKeys('brown.nuc')
ctrl=window['&open']
ctrl.Click()
i guess the problem is that the window which gets the input(#'please select a batch file menue') is not open at the beginning and the first part of the code opens it but python looks for it from the beginning and cant find it.
i really appreciate any suggestions how to solve this.

It looks like the window does not exist when the checking is performed. You should wait for a some time for window is opened.
try the next construction:
a_check = lambda: pywinauto.findwindows.find_windows(title=u' Please select a batch file to run:', class_name='#32770')[0]
try:
w_handle = pywinauto.timings.WaitUntilPasses(timeout=10, retry_interval=1, a_check)
except:
print('Something went wrong')
Also, your problem can be caused by the window has extra attributes/state. For example, inisible.
Use allowed argumens from find_windows to handle such cases, here the arguments list with defaul values:
pywinauto.findwindows.find_windows(class_name=None,class_name_re=None, parent=None, process=None, title=None, title_re=None, top_level_only=True, visible_only=True, enabled_only=False, best_match=None, handle=None, ctrl_index=None, predicate_func=None, active_only=False, control_id=None)

Related

Saving files in Python using "with" method

I am wanting to create a file and save it to json format. Every example I find specifies the 'open' method. I am using Python 2.7 on Windows. Please help me understand why the 'open' is necessary for a file I am saving for the first time.
I have read every tutorial I could find and researched this issue but with no luck still. I do not want to create the file outside of my program and then have my program overwrite it.
Here is my code:
def savefile():
filename = filedialog.asksaveasfilename(initialdir =
"./Documents/WorkingDirectory/",title = "Save file",filetypes = (("JSON
files","*.json"), ("All files", "*.")))
with open(filename, 'r+') as currentfile:
data = currentfile.read()
print (data)
Here is this error I get:
Exception in Tkinter callback Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1542, in call
return self.func(*args) File "C:\Users\CurrentUser\Desktop\newproject.py", line 174, in savefile
with open(filename, 'r+') as currentfile: IOError: [Errno 2] No such file or directory:
u'C:/Users/CurrentUser/Documents/WorkingDirectory/test.json'
Ok, I figured it out! The problem was the mode "r+". Since I am creating the file, there is no need for read and write, just write. So I changed the mode to 'w' and that fixed it. I also added the '.json' so it would be automatically added after the filename.
def savefile():
filename = filedialog.asksaveasfilename(initialdir =
"./Documents/WorkingDirectory/",title = "Save file",filetypes = (("JSON
files","*.json"), ("All files", "*.")))
with open(filename + ".json", 'w') as currentfile:
line1 = currentfile.write(stringone)
line2 = currentfile.write(stringtwo)
print (line1,line2)

How to take multiple screenshots through Selenium in Python?

GECKODRIVER_PATH = 'F:/geckodriver.exe'
firefox_options = Options()
firefox_options .add_argument("-headless")
driver = webdriver.Firefox(executable_path=CHROMEDRIVER_PATH, firefox_options = firefox_options )
test = []
test.append('http://google.com')
test.append('http://stackoverflow.com')
for x in test:
print x
driver.get(x)
driver.set_page_load_timeout(20)
filename = str(x)+'.png'
driver.save_screenshot( filename )
driver.close()
Now, how can I take multiple screenshots and save them in the different filename? As you can see I am trying to save the filename according to domain URL but failed.
See the error below:
http://google.com
http://card.com
Traceback (most recent call last):
File "F:\AutoRecon-master\test.py", line 125, in <module>
driver.get(x)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 326, in get
self.execute(Command.GET, {'url': url})
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 314, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: Tried to run command without establishing a connection
Can anyone please tell me what is the exact problem is? Will be a big help.
Try to move driver.close() out of loop:
for x in test:
print x
driver.get(x)
driver.set_page_load_timeout(20)
filename = str(x)+'.png'
driver.save_screenshot( filename )
driver.close()
Also note that x is already a string, so there is no need in str(x)
P.S. I'm not sure that http://stackoverflow.com.png filename is acceptable, you might need to use:
filename = x.split('//')[-1] + '.png'
Tried to run command without establishing a connection
you are closing the browser within your for loop... so the 2nd time through the loop it fails with the error above (since the browser is closed, the connection to geckodriver has already been terminated).
other issues:
you are setting the page_load_timeout after you have already fetched the page, so it is not doing anything useful.
using CHROMEDRIVER_PATH as the name for Geckodriver is just confusing. Chromedriver is not used at all here.

Renaming the log file at the end

In the beginning of the program the log file is named as:
filename='D://my_code_3/logging/'+timestr+'_XFR.log'
###set up logging to file
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',datefmt='%m-%d %H:%M',filename='D://my_code_3/logging/'+timestr+'_XFR.log', filemode='w')
During the execution of the program, various entries are made in this log file.
At the end of the program, it is required to rename the log file, to include a unique str variable (str9)captured by the program (which was initially unavailable at the beginning of the program execution, when the log file was just created). In order to rename the log file at the end of the program, the old_name log file has to be closed at first. I included these instructions in the following code:
fh = open('D://my_code_3/logging/'+timestr+'_XFR.log', "r")
print fh.read()
fh.close()
Then at the very end, I ask for a rename as below:
old_file ='D://my_code_3/logging/'+timestr+'_XFR.log'
new_file = 'D://my_code_3/logging/'+timestr+''+str9+'_XFR.log'
os.rename(old_file, new_file)
I get the following error message:
`
Traceback (most recent call last): File "qar_xfr_2017_10_05_WIP.py",
line 283, in
os.rename(old_file, new_file) WindowsError: [Error 32] The process cannot access the file because it is being used by another process`
I think that the old_file is still being written, and hence the message that th e file is open. If so, how can i provide a time delay before attempting to rename the old_file?
Thanks in advance for correcting / suggestion a solution.
All handlers need to be closed properly by calling
logging.shutdown()
After that you can rename the log file.

I don't understand how this "os.join" function is working? I am getting errors constantly and no reading on os functions is helping me

Here's the code
sys.path.append( "../tools/" )
from parse_out_email_text import parseOutText #(its just another .py file that has a function I wrote)
from_sara = open("from_sara.txt", "r")
from_chris = open("from_chris.txt", "r")
from_data = []
word_data = []
temp_counter = 0
for name, from_person in [("sara", from_sara), ("chris", from_chris)]:
for path in from_person:
### only look at first 200 emails when developing
### once everything is working, remove this line to run over full dataset
temp_counter += 1
if temp_counter < 200:
path = os.path.join('..', path[:-1]) #(THIS IS THE PART I CAN'T GET MY HEAD AROUND)
print path
email = open(path, "r")
email.close()
print "emails processed"
from_sara.close()
from_chris.close()
When I run this, it gives me an error as shown below:
Traceback (most recent call last):
..\maildir/bailey-s/deleted_items/101.
File "C:/Users/AmitSingh/Desktop/Data/Udacity/Naya_attempt/vectorize_text.py", line 47, in <module>
email = open(path, "r")
IOError: [Errno 2] No such file or directory: '..\\maildir/bailey-s/deleted_items/101.'
I don't even have this """'..\maildir/bailey-s/deleted_items/101.'""" directory path on my laptop, I tried to change the path by replacing the '..' in the code by the actual path name to the folder where I keep all the files, and nothing changes.
path = os.path.join('..', path[:-1])
This code is part of an online course on machine learning and I have been stuck at this point for 3 hours now. Any help would be really appreciated.
(P.S. This is not a homework question and there are no grades attached to this, its a free online course)
your test data is not there so it cannot find it. you should run start-up code again and make sure the necessary maildir are all there.
Go to tools inside your udacity project directory and run startup.py.
It is about 400 Mb so sit back and relax!
I know this is extremely late, but I found this post after having the exact same problem.
All the answers that I found here and on other sites, even the issue requests in the original github, were just "run startup.py" I already did that. However, it was telling me:
Traceback (most recent call last):
File "K:\documents\Udacity\Mini-Projects\ud120-projects\text_learning\vectorize_text.py", line 48, in <module>
email = open(path, "r")
FileNotFoundError: [Errno 2] No such file or directory: '..\\maildir/bailey-s/deleted_items/101.'
Just like yours. I then found where this file was located and it was indeed on my computer
I added 'tools' to the os.path.join() line as you can see here:
for name, from_person in [("sara", from_sara), ("chris", from_chris)]:
for path in from_person:
### only look at first 200 emails when developing
### once everything is working, remove this line to run over full dataset
temp_counter += 1
if temp_counter < 200:
#path = os.path.join('..', path[:-1]) <---original
path = os.path.join('..','tools', path[:-1])
print(path)
email = open(path, "r")
This worked for me finally. So, I hope it helps anyone else that stumbles on this problem in the future.
Also, I noticed on some examples I found of other repos of the lessons. Their 'tools' folder was named 'utils'.
Here is an example, this is a repo that someone tweaked to use jupyter notebooks to run the lessons So, use the one that you have.
In your Udacity course folder, first go to tools directory, check if you have maildir folder present and if it has got subfolders in it, if they are present then go back to text_learning/vectorize_text.py, find this line of code path = os.path.join('..', path[:-1]), change it to path = os.path.join('../tools/', path[:-1]),
On terminal, cd text_learning , then python vectorize_text.py, this should solve the issue.
If this does not solve the issue, then Go to tools inside your udacity project directory and run startup.py. Wait till the process is complete
Repeat step 1.

Web2py application: How to reference .yaml file in controller?

I have an app running online under web2py. Now, i am adding names.yml file which i need to call in my controller file (default.py) on web2py server. where should I keep the .yml/.yaml files. Currently I have kept them in views with default/names.yml but when I call it in default.py like:
dicttagger = DictionaryTagger([ 'default/names.yml', 'default/surname.yml'])
i get no such file error.
Also tried below:
dicttagger = DictionaryTagger([ 'views/default/names.yml', 'views/default/surname.yml'])
same error
class snapshot as under:
class DictionaryTagger(object):
def __init__(self, dictionary_paths):
files = [open(path, 'r') for path in dictionary_paths]
dictionaries = [yaml.load(dict_file) for dict_file in files]
map(lambda x: x.close(), files)
Any suggestions as how to do this or am I making mistake of using yaml/yml file in we2py and it doesn't work in web2py app hosted online?
question 2
thank you. it resolved an error but I am not sure how to add nltk.download() into my hosted app. I keep getting the below error. Can you pls have a look:
Traceback
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
Traceback (most recent call last):
File "/home/prakashsukhwal/web2py/gluon/restricted.py", line 220, in restricted
exec ccode in environment
File "/home/prakashsukhwal/web2py/applications/Sensiva/controllers/default.py", line 4, in
nltk.download()
File "/usr/local/lib/python2.7/dist-packages/nltk/downloader.py", line 644, in download
self._interactive_download()
File "/usr/local/lib/python2.7/dist-packages/nltk/downloader.py", line 958, in _interactive_download
DownloaderShell(self).run()
File "/usr/local/lib/python2.7/dist-packages/nltk/downloader.py", line 981, in run
user_input = raw_input('Downloader> ').strip()
EOFError: EOF when reading a line
Error snapshot help
(EOF when reading a line)
inspect attributes
Frames
File /home/prakashsukhwal/web2py/gluon/restricted.py in restricted at line 220 code arguments variables
File /home/prakashsukhwal/web2py/applications/Sensiva/controllers/default.py in at line 4 code arguments variables
File /usr/local/lib/python2.7/dist-packages/nltk/downloader.py in download at line 644 code arguments variables
File /usr/local/lib/python2.7/dist-packages/nltk/downloader.py in _interactive_download at line 958 code arguments variables
File /usr/local/lib/python2.7/dist-packages/nltk/downloader.py in run at line 981 code arguments variables
Function argument list
(self=)
Code listing
def run(self):
print 'NLTK Downloader'
while True:
self._simple_interactive_menu(
'd) Download', 'l) List', ' u) Update', 'c) Config', 'h) Help', 'q) Quit')
user_input = raw_input('Downloader> ').strip()
if not user_input: print; continue
command = user_input.lower().split()[0]
args = user_input.split()[1:]
try:
Variables
user_input undefined
builtinraw_input
).strip undefined
Context
You can store the files wherever you want, but if you're using the Python open function, you'll need to give it full paths, not paths relative to the web2py application folder. Instead, try:
import os
dicttagger = DictionaryTagger([os.path.join(request.folder, 'views',
'default', 'names.yml'),
...])