Renaming the log file at the end - python-2.7

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.

Related

unboundLocalError:local variable 'connSkt' referenced before assginment

I am writing some codes to scan ports with Python. However, the error keeps showing up, I am not sure how to fix.
Error is listed below:
[+] Scan Results for: ubuntu
[-] 80/tcp closed
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "portscanner.py", line 23, in connScan
connSkt.close()
UnboundLocalError: local variable 'connSkt' referenced before assignment
I did some research and appeared that I did not declare the variable properly, but I double checked the code and could not see what is wrong with it. Here is the tutorial I followed:
https://www.youtube.com/watch?v=IOvvjNi8OdU&list=PL1A2CSdiySGLtKwqBnqj9BON6QQjWkP4n&index=5
def connScan(tgtHost,tgtPort):
try:
connSkt = socket(AD_INET, SOCKET_STREAM)
connSkt.connect((tgtHost,tgtPort))
connSkt.send('Hello\r\n')
results = connSkt.recv(100)
screenLock.acquire()
print "[+] "+ str(tgtPort) + "/tcp open"
except:
screenLock.acquire()
print "[-] "+ str(tgtPort) + "/tcp closed"
finally:
screenLock.release()
connSkt.close()`
any advise would be highly appreciated. Thanks in advance!
When socket creation fails with an exception, the variable connSkt is not yet created/defined in the Python interpreter. In that case, the call to close in the "finally" clause, is being invoked on an undefined variable. Hence, the interpreter is complaining.
Responding to follow-up question, one way to avoid this in the above (using LYBL approach):
connSkt = None
try:
...
except:
...
finally:
screenLock.Release()
if connSkt:
connSkt.close()
An EAFP approach might catch the exception but with my C-background, I am not quite comfortable catching exception for UnboundLocalError.

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.

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'),
...])

pywinauto batch file running error

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)