More than a month ago I've added this script to my startup applications. It worked just like it should, every single time.
Now, for some reason, it's not working every single time (primarily it's not working every single time in the morning, there are different variations now).
I've changed the interpreter, shortened paths - it didn't help. And when nothing happens, after (and before) typing a command to find all working python processes
ps -fA | grep python
this process is there.
I'm on Linux Mint 18.3 MATE. Thanks.
#! /usr/bin/python3
"""My Alarms."""
import schedule
import time
import webbrowser
import subprocess
def breakfast():
"""Breakfast reminder."""
subprocess.Popen(['notify-send', 'TIME TO EAT BREAKFAST'])
webbrowser.open('/path_to/carbon.ogg')
def dinner():
"""Dinner reminder."""
subprocess.Popen(['notify-send', 'TIME TO MAKE A DINNER'])
webbrowser.open('/path_to/carbon.ogg')
def shut_down():
"""Shut Down (Laptop) reminder."""
subprocess.Popen(['notify-send', 'TIME TO SHUT DOWN THE PC'])
webbrowser.open('/path_to/carbon.ogg')
schedule.every().day.at("07:35").do(breakfast)
schedule.every().day.at("17:10").do(dinner)
schedule.every().day.at("21:00").do(shut_down)
while True:
schedule.run_pending()
time.sleep(1)
Turns out, I haven't met requirements for the schedule module. Some of these modules were updated, some were missing. Now it's working like it used to be. Case closed.
Related
app = Application(backend="uia").start("program.exe")
I am using pywinauto to do some tasks indefinitely. However, occasionally, I need to restart the script for some external reasons. When this happens, I would like to keep the created applications open. How can I do this? I noticed if the python script errors out, the applications will stay open. But if I exit the script manually, the windows will close. So there must be some way to accomplish this.
I think pywinauto's Application.start cannot do the work. You can try:
pid = os.spawnl(os.P_NOWAIT, "program.exe")
app = Application().connect(process=pid)
os.spawnl is considered deprecated. Use subprocess module.
Combining the answer in Run a program from python, and have it continue to run after the script is killed and pywinauto official doc, you can do this:
subprocess.Popen(
['your_program', 'with args'],
# These will make sure the desktop program will alive even when shell session terminates.
creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP, shell=True
)
desktop = Desktop(backend="uia")
main_win = desktop.window(title="program's window title", control_type="Window")
Why not use system command:
#Use multiple thread to avoid block of system function
import _thread as qd
import os
qd.start_new_thread(os.system,('notepad',))
from pywinauto import Application
#connect pywinauto with application via title regular expression
win=Application(backend='uia').connect(title_re='.*Notepad.*')
Then you use pywinauto to connect application via title?
So I have this GUI that I made with tkinter and everything works well. What it does is connects to servers and sends commands for both Linux or Windows. I went ahead and used pyinstaller to create a windowed GUI without console and when I try to uses a specific function for sending Windows commands it will fail. If I create the GUI with a console that pops up before the GUI, it works like a charm. What I'm trying to figure out is how to get my GUI to work with the console being invisible to the user.
The part of my code that has the issue revolves around subprocess. To spare you all from the 400+ lines of code I wrote, I'm providing the specific code that has issues. Here is the snippet:
def rcmd_in(server):
import subprocess as sp
for i in command_list:
result = sp.run(['C:/"Path to executable"/rcmd.exe', '\\\\' + server, i],
universal_newlines=True, stdout=sp.PIPE, stderr=sp.STDOUT)
print(result.stdout)
The argument 'server' is passed from another function that calls to 'rcmd_in' and 'command_list' is a mutable list created in the root of the code, accessible for all functions.
Now, I have done my due diligence. I scoured multiple searches and came up with an edit to my code that makes an attempt to run my code with that console invisible, found using info from this link: recipe-subprocess. Here is what the edit looks like:
def rcmd_in(server):
import subprocess as sp
import os, os.path
si = sp.STARTUPINFO()
si.dwFlags |= sp.STARTF_USESHOWWINDOW
for i in command_list:
result = sp.run(['C:/"Path to executable"/rcmd.exe', '\\\\' + server, i],
universal_newlines=True, stdin=sp.PIPE, stdout=sp.PIPE,
stderr=sp.STDOUT, startupinfo=si, env=os.environ)
print(result.stdout)
The the problem I have now is when it runs an error of "Error:8 - Internal error -109" pops up. Let me add I tried using functions 'call()', 'Popen()', and others but only 'run()' seems to work.
I've reached a point where my brain hurts and I can use some help. Any suggestions? As always I am forever great full for anyone's help. Thanks in advance!
I figured it out and it only took me 5 days! :D
Looks like the reason the function would fail falls on how Windows handles stdin. I found a post that helped me edit my code to work with pyinstaller -w (--noconsole). Here is the updated code:
def rcmd_in(server):
import subprocess as sp
si = sp.STARTUPINFO()
si.dwFlags |= sp.STARTF_USESHOWWINDOW
for i in command_list:
result = sp.Popen(['C:/"Path to executable"/rcmd.exe', '\\\\' + server, i],
universal_newlines=True, stdin=sp.PIPE, stdout=sp.PIPE,
stderr=sp.PIPE, startupinfo=si)
print(result.stdout.read())
Note the change of functions 'run()' to 'Popen()'. The 'run()' function will not work with the print statement at the end. Also, for those of you who are curious the 'si' variable I created is preventing 'subprocess' from opening a console when being ran while using a GUI. I hope this will become useful to someone struggling with this. Cheers
I am making a text editor and want to add a feature of IDLE in my app. So i want an frame with python IDLE embedded in it with all menus and features which original python IDLE gives.
I looked in source of idle lib but cannot find a solution.
try:
import idlelib.pyshell
except ImportError:
# IDLE is not installed, but maybe pyshell is on sys.path:
from . import pyshell
import os
idledir = os.path.dirname(os.path.abspath(pyshell.__file__))
if idledir != os.getcwd():
# We're not in the IDLE directory, help the subprocess find run.py
pypath = os.environ.get('PYTHONPATH', '')
if pypath:
os.environ['PYTHONPATH'] = pypath + ':' + idledir
else:
os.environ['PYTHONPATH'] = idledir
pyshell.main()
else:
idlelib.pyshell.main()
This code is of pyshell.pyw found under idlelib folder in all python install
I searched the idle.pyw and found that it uses a program pyshell which is real shell. So how can i embed it.
I want a Tkinter frame with python IDLE shell embedded in it.Please give the code. Thanks in advance.
idlelib implements IDLE. While you are free to use it otherwise, it is private in the sense that code and interfaces can change in any release without the usual back-compatibility constraints. Import and use idlelib modules at your own rish.
Currently, a Shell window is a Toplevel with a Menu and a Frame. The latter has a Text and vertical Scrollbar. It is not possible to visually embed a Toplevel within a frame (or within another Toplevel or root = Tk()). top = Toplevel(myframe) works, but top cannot be placed, packed, or gridded within myframe.
I hope in the future to refactor editor.py and pyshell.py so as to separate the window with menu from the frame with scrollable text. The result should include embeddable EditorFrame and ShellFrame classes that have parent as an arguments. But that is in the future.
Currently, one can run IDLE from within python with import idlelib.idle. However, because this runs mainloop() (on its own root), it blocks and does not finish until all IDLE windows are closed. This may not be what one wants.
If having Shell run in a separate window is acceptable, one could extract from python.main the 10-20 lines needed to just run Shell. Some experimentation would be needed. If the main app uses tkinter, this function should take the app's root as an argument and not call mainloop().
Tcl having Tkcon.tcl . when each thread source (means run/exec) the Tkcon.tcl
each thread will pop up a Tk shell/Tk console/tkcon.tcl very good idea for debug. and print message individually by thread.
Python having idle.py ... and how to use it ? still finding out the example .
The are same Tk base . why can't find an suitable example? so far ... keep finding...
I have a python script in file called tasks.py containing multiple tasks, processes and functions (and it works perfect to me).
i want to run this file (tasks.py) at certain time ( 1:00 am & 4:45 am & 11:35 am & 6:25 pm & 9:10 pm) every day starting from date say as example 6 aug 2018.
so i created a new file and called it run.py
i used the following code to import tasks.py file
#!/usr/bin/python
import tasks
but i want to schedule this import in the certain times as mentioned above starting from the required date
i tried while function, schedule module, cron module and import os but i failed with all
any body can help please ????
The simple solution can be something like that
import datetime
from time import sleep
rest_seconds = 3600 # sleep for one hour, so the task won't be called few times per hour
while True:
if datetime.datetime.now().hour == 12:
do_task()
sleep(rest_seconds)
If you need a complex one, I use Airflow framework for building scheduled tasks/pipelines
Hi everyone i am trying to build a file watcher in python 3.5 using watchgod. I want to continuously watch a directory and if any file is added then i want to send a list of added files to another program which will perform a series of task. Following is my code in python :-
print("execution of main file begins !!!!")
import os
from watchgod import watch
#changes gives a set object when watch finds any kind of changes in directory
for changes in watch(r'C:\Users\Rajat.Malik\Desktop\Requests'):
fileStatus = [obj[0] for obj in list(changes) ] #converting set to list which gives file status as added, changed or modified
fileLocation = [obj[1] for obj in list(changes) ] #similarly getting list of location of files added
var2 = 0
for var1 in fileLocation:
if fileStatus[var2] == 1: #if file is added then passing all files to another code which will work on the list of files added
os.system('python split_thread_module.py '+var1) #now this code will start executing
var2 = var2 + 1
So the problem i am having is that while split_thread_module.py is executing the watcher is not watching the directory. Any file which is coming at time when split_thread_module.py is executing is not reflecting in changes. How can i watch the changes in directory and pass it to the other program on the fly even when the other program is executing. I am not a python programmer. Can anyone help me in this regard ?
Thanks in advance !!!!
Sorry for delayed, I'm the developer of watchgod. I've added a python-watchgod tag to your question which I'll watch (no pun intended) in future so I can answer such questions more quickly.
To answer your question, watchgod will not miss changes which occur in the filesystem while other code is running. They'll just be reported as changes next time watch iterates.
More generally the best approach would be to run the other code asynchronously so the main process can get back to watching the directory.
a few other hints for neater python
no need to call list(changes) in the comprehension
os.system is deprecated, better to use subprocess.run
since split_thread_module.py is also python, do you really need to run it in a separate process? Even if you do you might have more luck with python multiprocessing than starting a new process with the system's process initiation.
Overall you might try something like:
from concurrent.futures import ProcessPoolExecutor
from time import sleep
from watchgod import watch
def slow_job(status, location):
print(f'status: {status}, location: {location}, starting...')
sleep(10)
print(f'status: {status}, location: {location}, done')
with ProcessPoolExecutor() as executor:
for changes in watch('./tests'):
for status, location in changes:
executor.submit(slow_job, status, location)