why does os.startfile not open up requested file - python

Hi can anyone help me set up a task . I want to automate a task to open an app at a specific time but for now i'm just trying to open an app with my code but when i try to run it in vscode i have to type the file name into the terminal for it to open .
def openFile():
try:
os.startfile(r"C:\Users\user\Documents>hi.txt")
except Exception as e:
print(str(e))

The problem was that it was running too fast
I added a time function and it's running perfectly now
while os.startfile(r"C:\Users\user\Documents\hi.txt"):
print("I'm going to wait 5 seconds now!")
time.sleep(5)

Related

Never-ending file existence check loop

I'm sorry, I'm a complete beginner but very fascinated by scripting automation. I'm trying to check for the existence of a file that arrives once in a while. I want to read it and then delete it. I can't figure out how to keep this action running without the goto Label feature.
Can anyone advise me please?
import os
import os.path
import time
path = os.path.exists('file.txt')
#loop
if path is True:
print("File exists.")
time.sleep(1)
os.remove("file.txt") # Remove the file.
# Now I need to start the loop again.
else:
print("File doesn't exist")
time.sleep(1)
# Now I need to start the loop again.
# And keep it running forever.
This is what "while" loops are for.
import os.path
import time
while True:
time.sleep(1)
if os.path.exists('file.txt'):
print("File exists.")
os.remove("file.txt") #remove the file.
else:
print("File doesn't exist")
You can do this with a batch file. You don't need Python.
I think what you are looking for is a folder monitor which performs actions based on the event handling in the folder. I recommend using the 'watchdog' library in python to monitor the folder for incoming or outgoing files while the 'subprocess' library executes actions like reading and deleting. Refer to the code below
Code:
import subprocess
import time
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
def on_created(event):
print("A File is arrived",os.path.basename(event.src_path))
time.sleep(10)
os.remove(event.src_path)
def on_deleted(event):
print("File Deleted")
if __name__ == "__main__":
event_handler= FileSystemEventHandler()
event_handler.on_created=on_created
event_handler.on_deleted=on_deleted
path="A:/foldername" #"Enter the folder path" you want to monitor here
observer= Observer()
observer.schedule(event_handler,path,recursive=False) #If recursive is set to be True it will check in the subdirectories for contents if a folder is added to our path
observer.start()
try:
while True:
time.sleep(15) # Sleeps for 15 seconds
except KeyboardInterrupt:
observer.stop() # The code terminates if we hit any key in the folder or else it keeps running for ever
observer.join()
Also, if you want to read the file before deleting then add the file reading code in the on_created method before "os.remove" and the code should work fine for you now!

Restart python program whenever it encounters an exception

So I've got a selenium python script that occasionally runs into the following error at differing sections in my code:
Exception has occurred: WebDriverException
Message: unknown error: cannot determine loading status
from target frame detached
But when I encounter this error, if I re-run the program without changing anything, everything works again (so I know that it's either a problem with the website or the webdriver). In the meantime, I was wondering if there was a way to tell python to restart the program if a WebDriverException is encountered. Any help would be greatly appreciated, thank you.
You could try os.execv(), according to here, it enables a python script to be restarted, but you need to clean the buffers etc using this C-like function sys.stdout.flush()
try:
<your block of code>
except WebDriverException:
print(<Your Error>)
import os
import sys
sys.stdout.flush()
os.execv(sys.argv[0], sys.argv)
You could simply use the os module to do this: os.execv(sys.argv[0], sys.argv)
Use a main() function as a starting point for your program, and trigger that function again whenever you need to restart. Something like
def foo1():
return
def foo2():
try:
...
except:
main()
def main():
foo1()
foo2()
if __name__ == "main":
main()
If the error occurs because it does not find a certain tag, you could put a wait
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
or worst case
browser.implicitly_wait(5)
or
time.sleep(5)
which waits 5 seconds for the element to appear

python wget library not returning if internet goes down for some times. How can I return with error if Internet is down?

I have below code to download a file inside a loop,
import wget
try:
wget.download(url)
except:
pass
But if the Internet goes down, it doesn't return!
So my whole loop is stuck.
I want to repeat the same download if internet goes down. So I wanna know does any error happen.
How can i mitigate this?
One simple solution is to move your download code to a thread and make it a separate process which can be interrupted.
You can use python Thread and Timer module to achieve it.
from threading import Thread, Timer
from functools import partial
import time
import urllib
def check_connectivity(t):
try:
urllib.request.urlopen("http://google.com", timeout=2)
except Exception as e:
t._Thread__stop()
class Download(Thread):
def run(self):
print("Trying to download file....")
con = partial(check_connectivity, self)
while True:
t = Timer(5, con) # Checks the connectivity every 5 second or less.
t.start()
# your download code....
def main():
down = Download()
down.start()
down.join()
You code move your main download loop inside the thread's run method. And start a timer inside which listens for the network connectivity.

Flask API - Auto Exit

i am making an Flask-API for my project and i want to achieve something when the server restarts or runs, meaning whenever the main block is executed i want to do a check.
the code:
if __name__ == '__main__':
try:
with open('x.p','rb') as pkl_PR:
ps=pickle.load(pkl_PR)
with open('y.p','rb') as pkl_df:
df=pickle.load(pkl_df)
with open('z.p','rb') as pkl_spl:
spl_df = pickle.load(pkl_spl)
except Exception as e:
logger.debug(e)
app.run(debug=True)
so if any one of the pickle file doesn't exist, i dont want to start the server and save a log file with error.
so how do i go about it?
You can call sys.exit() from inside the except block, that will cause your program to exit before starting the flask server.

How to handle console exit and object destruction

Given this code:
from time import sleep
class TemporaryFileCreator(object):
def __init__(self):
print 'create temporary file'
# create_temp_file('temp.txt')
def watch(self):
try:
print 'watching tempoary file'
while True:
# add_a_line_in_temp_file('temp.txt', 'new line')
sleep(4)
except (KeyboardInterrupt, SystemExit), e:
print 'deleting the temporary file..'
# delete_temporary_file('temp.txt')
sleep(3)
print str(e)
t = TemporaryFileCreator()
t.watch()
during the t.watch(), I want to close this application in the console..
I tried using CTRL+C and it works:
However, if I click the exit button:
it doesn't work.. I checked many related questions about this but it seems that I cannot find the right answer..
What I want to do:
The console can be exited while the program is still running.. to handle that, when the exit button is pressed, I want to make a cleanup of the objects (deleting of created temporary files), rollback of temporary changes, etc..
Question:
how can I handle console exit?
how can I integrate it on object destructors (__exit__())
Is it even possible? (how about py2exe?)
Note: code will be compiled on py2exe.. "hopes that the effect is the same"
You may want to have a look at signals. When a *nix terminal is closed with a running process, this process receives a couple signals. For instance this code waits for the SIGHUB hangup signal and writes a final message. This codes works under OSX and Linux. I know you are specifically asking for Windows but you might want to give it a shot or investigate what signals a Windows command prompt is emitting during shutdown.
import signal
import sys
def signal_handler(signal, frame):
with open('./log.log', 'w') as f:
f.write('event received!')
signal.signal(signal.SIGHUP, signal_handler)
print('Waiting for the final blow...')
#signal.pause() # does not work under windows
sleep(10) # so let us just wait here
Quote from the documentation:
On Windows, signal() can only be called with SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, or SIGTERM. A ValueError will be raised in any other case.
Update:
Actually, the closest thing in Windows is win32api.setConsoleCtrlHandler (doc). This was already discussed here:
When using win32api.setConsoleCtrlHandler(), I'm able to receive shutdown/logoff/etc events from Windows, and cleanly shut down my app.
And if Daniel's code still works, this might be a nice way to use both (signals and CtrlHandler) for cross-platform purposes:
import os, sys
def set_exit_handler(func):
if os.name == "nt":
try:
import win32api
win32api.SetConsoleCtrlHandler(func, True)
except ImportError:
version = “.”.join(map(str, sys.version_info[:2]))
raise Exception(”pywin32 not installed for Python ” + version)
else:
import signal
signal.signal(signal.SIGTERM, func)
if __name__ == "__main__":
def on_exit(sig, func=None):
print "exit handler triggered"
import time
time.sleep(5)
set_exit_handler(on_exit)
print "Press to quit"
raw_input()
print "quit!"
If you use tempfile to create your temporary file, it will be automatically deleted when the Python process is killed.
Try it with:
>>> foo = tempfile.NamedTemporaryFile()
>>> foo.name
'c:\\users\\blah\\appdata\\local\\temp\\tmpxxxxxx'
Now check that the named file is there. You can write to and read from this file like any other.
Now kill the Python window and check that file is gone (it should be)
You can simply call foo.close() to delete it manually in your code.

Categories