Launching a .exe Upon a Timer's Due_Date - python

How Would i Go About Adding a File To launch when it see that's it's the due_date? I've try'd quite i few different method's from Google but i'm still having a hard time figuring it out. currently it's set to wait 36 hours after launching the .py file.
any help would be great and it'd get this monkey off my back for good!
import datetime
import croniter
import crontab
import time
c = croniter.croniter("0 9,10,11 * * TUE")
next_due_date = c.get_next(datetime.datetime)
while True:
now = datetime.datetime.now()
if now > next_due_date:
do_something(line.py)
time.sleep(60 * 60 * 36)
else:
time.sleep(60 * 60 * 2)

If it's a .exe you can just use os.system("myexecutable.exe") after launching the python
import datetime
import croniter
import crontab
import time
c = croniter.croniter("0 9,10,11 * * TUE")
next_due_date = c.get_next(datetime.datetime)
while True:
now = datetime.datetime.now()
if now > next_due_date:
do_something(line.py) # Edit: fixed tabbing; just in case it wasn't tabbed in
# your script
# Use os.system to run the exe
os.system("myexecutable.exe")
time.sleep(60 * 60 * 36)
else:
time.sleep(60) # Edit: I always find that it's better to have a smaller
# sleep time
You can also use the subprocess module so you can halt the script or track if the exe is still running instead.

Related

Why does my .exe generated by PyInstaller not start?

I generated an executable file with PyInstaller, but when I want to launch the application the console window shows me, that it couldn't find a directory or file. I checked the location and the folder "_MEI55762" is indeed not present.
Did anyone have this issue before?
Below the part of the code, where I think the error should be located. I think it has something to do with the imports of the "jsonrpclcient" package. I didnĀ“t post the full code with the all the GUI lines, since I think it will not help. If I am wrong please let me know.
import os
import sys
import requests
import json
import pyvisa
import time
from datetime import datetime
import threading
import signal
from jsonrpcclient import *
from jsonrpcclient.clients.http_client import HTTPClient
from jsonrpcclient.requests import Request
from tkinter import *
from tkinter import ttk
import traceback
print("-----------------------------------------")
print(" Q-Center V0.1 ")
print("-----------------------------------------")
port = ":8080"
rm = pyvisa.ResourceManager()
def listArticles():
for attempt in range (3): #Will be executed 3 times in case an error occurs
print('List Articles:')
try: #First try this
client = HTTPClient("http://" + ipEntry.get() + port)
response = client.send(Request("list_articles"), timeout=5)
print(response.data.result)
print('Success!')
except: #If an error occurs, call the print function and let the user know
print('An error occured!')
rebootPeacock()
else: #If no error occurs, stop trying
break
else: #If no attempt was successful, print that all 3 attempts failed. ONLY EXCUTED WHEN THE LOOP DOES'T BREAK.
print('All 3 attempts failed!')
answer = response.data.result
pkReply.insert(END, answer)
pkReply.insert(END, '\n\n')
The solution is to tell PyInstaller to add the "response-schema.json" file which is located at "C:\Users\pfra\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\jsonrpcclient".
So the command should look like:
pyinstaller --add-file "C:\Users\pfra\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\jsonrpcclient.response.schema.json;."

Python crontab adding newline character automatically and disabling other cron job

I've written a python script to run certain cron jobs and using crontab for the same.
Following is the code snippet:
import os
import inspect
from crontab import CronTab
def add_cron_job(scripts_list,frequency):
my_cron = CronTab(user='simrat')
for script in scripts_list:
if not cron_exists(my_cron,script):
command = 'python {}'.format(script)
job = my_cron.new(command=command, comment=script)
job.minute.every(frequency)
my_cron.write()
def cron_exists(my_cron, script):
for job in my_cron:
if job.comment == script:
return True
return False
if __name__ == "__main__":
#Frequency of every 1 minute
test_script = ['test1.py', 'test2.py']
add_cron_job(test_script,1)
#Frequency of every 1 day
test_script2 = ['test3.py']
add_cron_job(test_script2,1440)
Following is the output of 'crontab -e' (notice additional spaces added)
* * * * * python test1.py # test1.py
* * * * * python test2.py # test2.py
*/1440 * * * * python test3.py # test3.py
When I re-run the python cron_job script, it somehow disables the last cron_job(test3.py) and following is the output of crontab file:
* * * * * python test1.py # test1.py
* * * * * python test2.py # test2.py
# DISABLED LINE
# */1440 * * * * python test3.py # test3.py
*/1440 * * * * python test3.py # test3.py
along with an error it throws on console:
No handlers could be found for logger "crontab"
So my question is 3 fold:
Why is additional space at the top of the command when running my_cron.write()?
Why does it disable the last cron job instead of ignoring it as it already exists (def cron_exits should have taken care of that)
What's the signifance of the error thrown?
I ran you code and got following error in second run:
'1440', not in 0-59 for Minutes
I changed 1440 to 14 and ran code multiple times. And found same code every time (without deleting)
* * * * * python test1.py # test1.py
* * * * * python test2.py # test2.py
*/14 * * * * python test3.py # test3.py
I have not read complete CronTab code but it is clear that they have put some validator during reading existing cron commands but they are not validating it during writing.
Also i called add_cron_job with different arguments and found each time my_cron.write() is called it is adding a new line. This is not a bug but a feature.
Finally
No handlers could be found for logger "crontab" is logging issue. Try this Crontab Logger issue

python script slow after base64 module import

I am trying to generate keys using os.urandom() and base64 methods. Please see the below code. gen_keys() itself may not be very slow, but
the script overall run time is very slow. For example, gen_keys() takes
about 0.85 sec where as the overall script run time is is 2 minutes 6 seconds. I suspect this is some thing to do with module imports. Although I need all of the modules from my script.
Any thoughts on the real issue? Thanks.
I am using python3.4
#!/usr/bin/env python3
import netifaces
import os
import subprocess
import shlex
import requests
import time
import json
import psycopg2
import base64
def gen_keys():
start_time = time.time()
a_tok = os.urandom(40)
a_key = base64.urlsafe_b64encode(a_tok).rstrip(b'=').decode('ascii')
s_tok = os.urandom(64)
s_key = base64.urlsafe_b64encode(s_tok).rstrip(b'=').decode('ascii')
print("a_key: ", a_key)
print("s_key: ", s_key)
end_time = time.time()
print("time taken: ", end_time-start_time)
def Main():
gen_keys()
if __name__ == '__main__':
Main()
$~: time ./keys.py
a_key: 52R_5u4I1aZENTsCl-fuuHU1P4v0l-urw-_5_jCL9ctPYXGz8oFnsQ
s_key: HhJgnywrfgfplVjvtOciZAZ8E3IfeG64RCAMgW71Z8Tg112J11OHewgg0r4CWjK_SJRzYzfnN-igLJLRi1CkeA
time taken: 0.8523025512695312
real 2m6.536s
user 0m0.287s
sys 0m7.007s
$~:

How to run python file in cron job

I need to run this file:
from apps.base.models import Event
from apps.base.models import ProfileActiveUntil
from django.template import Context
from django.db.models import Q
import datetime
from django.core.mail import EmailMultiAlternatives
from bonzer.settings import SITE_HOST
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from bonzer.settings import send_mail, BONZER_MAIL, BONZER_MAIL_SMTP, BONZER_MAIL_USER, BONZER_MAIL_PASS, BONZER_MAIL_USETLS
today = datetime.date.today()
monthAgo = today + datetime.timedelta(days=1)
monthAgoMinusOneDay = today + datetime.timedelta(days=2)
events = Event.objects.all()
ProfileActiveUntils = ProfileActiveUntil.objects.filter(Q(active_until__range=(monthAgo, monthAgoMinusOneDay)))
msg = MIMEMultipart('alternative')
msg['Subject'] = "Novim dogodivscinam naproti"
msg['From'] = BONZER_MAIL
msg['To'] = 'jjag3r#gmail.com'
text = u'bla'
html = u'bla'
send_mail(msg_to=msg['To'], msg_subject=msg['Subject'], msg_html=html, msg_text=text)
I execute it like this: */2 * * * * /usr/local/bin/python2.7 /home/nezap/webapps/bonzer/bonzer/apps/base/alert.py
But I get error: No module named apps.base.models.
Important fact is that I can't install virtualenv on server because I don't have permissions. Also I'm kind of newbie on this stuff so I don't have a lot of skills on servers or python.
Thank you.
cron does not read rc shell files so you need to define the enviroment variable PYTHONPATH to include the location of the apps package and all other module files that are required by the script.
PYTHONPATH=/usr/local/lib/python2.7:/usr/lib/python2.7
*/2 * * * * /usr/local/bin/python2.7 /home/nezap/webapps/bonzer/bonzer/apps/base/alert.pyr
I would assume this is a problem with your cwd (current working directory). An easy way to test this would be to go to the root (cd /) then run:
python2.7 /home/nezap/webapps/bonzer/bonzer/apps/base/alert.py
You should get the same error. The path you will want to use will depend on the place where you normally run the script from. I would guess it would either be:
/home/nezap/webapps/bonzer/bonzer/apps/base
or
/home/nezap/webapps/bonzer/bonzer/
So your solution would either be:
*/2 * * * * cd /home/nezap/webapps/bonzer/bonzer/apps/base && /usr/local/bin/python2.7 ./alert.py
or
*/2 * * * * cd /home/nezap/webapps/bonzer/bonzer && /usr/local/bin/python2.7 ./apps/base/alert.py
basically you are telling cron to change directory to that path, then if that works(the &&) run the following command.

Opening files with Pydbg while application is running

Using pydbg I'm opening files(ex. c:\\myfile.mnp) within a win32 application(Ex. c:\\myprog.exe) in this way.
dbg = pydbg()
dbg.load("c:\\myprog.exe", "c:\\myfile1.mnp")
If the target application is already running then, is it possible to open a another file(For example c:\myfile2.mnp ) within the same application which is already running without closing that process/apps, using pydbg?
From personal experience, its better to have python start the application, or attach to it while its running.
import pydbg
from pydbg import *
from pydbg.defines import *
import struct
import utils
dbg = pydbg()
pid = ''
name = ''
found_program = False
for (pid, name) in dbg.enumerate_processes():
if name.lower() == "program.exe":
found_program = True
dbg.attach(pid)
if found_program:
dbg.run()
To make python start it:
from os import system
system('start "c:\program.exe"')

Categories

Resources