run cron job web2py under pythonanywhere - python

let take a example , i want to run a mail function from scheduler. i made mail.py under the modules
from gluon.tools import Mail
mail=Mail()
mail.settings.server='smtp.gmail.com:587'
mail.settings.login='ass.aa#gmail.com:aaaaaa'
mail.settings.sender='aaa.aa#aa.com'
mail.send(to=['aaa#aaa.a,'],
subject='aaaaaa',
message='<html>'
'<body>'
'test mail'
'</body>'
'</html>')
my corntab file is
0-59/1 * * * * root *applications/comv1/modules/mail1.py
scheduler.py file which under home > application name of pythonanywhwer
#/usr/bin/env python
import os
import socket
import sys
import subprocess
filename = os.path.abspath(__file__) # we use this to generate a unique socket name
try:
socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM).bind('\0' + filename)
except socket.error:
print("Failed to acquire lock, task must already be running")
sys.exit()
subprocess.call(["python", "web2py/web2py.py", "-K", "comv3"])
after this also i am not able to run cron job.....
can any one help me

PythonAnywhere does not read crontab. If you want to run a task periodically, we provide Scheduled tasks. There are docs about how to use them on our help pages.

Related

Python script runs fine from terminal but crashes when run from crontab

I have a simple python script that takes screenshots of a computer that is running Ubuntu. I want it to run automatically on startup, so I put #reboot python3 /bin/program.py in the non-sudo version of crontab.
The program works fine when run from terminal, but gives the error pyscreenshot.err.FailedBackendError. I put it in a try loop, and had it write all exceptions to a file, and that's how I found the error message, "All backends failed."
It has something to do with the program 'pyscreenshot' not working correctly.
import pyscreenshot as screen
import os
from numpy import random
from time import sleep
from os.path import expanduser
TMP_SCREEN_PATH = expanduser('~') + '/.UE/tmp.png'
LOG_FILE_PATH = expanduser('~') + '/.UE/log.txt'
GRAB_DELAY_RANGE = (1, 10)
def screenshot(save_path=TMP_SCREEN_PATH):
img = screen.grab()
img.save(save_path)
def delay(delay_range):
sleep_time = random.randint(delay_range[0], delay_range[1])
print(f"Sleeping for {sleep_time} seconds")
sleep(sleep_time)
def main():
try:
while True:
screenshot()
delay(GRAB_DELAY_RANGE)
except KeyboardInterrupt:
print("Nope")
main()
except Exception as e:
print(e)
with open(LOG_FILE_PATH, 'a') as f:
f.write(str(type(e))+str(e)+'\n')
sleep(5)
main()
f = open(LOG_FILE_PATH, 'w+')
f.write('Startup')
f.close()
main()
I need one of the following solutions:
Simply fix the problem
Another way to run a program at startup
A different module to take screenshots with
Any help is appreciated, thanks
If the user that the cron job runs as is also logged in on the console (you mention a reboot, so I'm guessing that you have enabled autologin), then your cron job might work if you also add:
os.environ["DISPLAY"] = ":0"
This worked for me on Ubuntu in a test using cron and a simplified version of your script:
import os
import pyscreenshot as screen
os.environ["DISPLAY"] = ":0"
img = screen.grab()
img.save("/tmp/test.png")
If it doesn't work for you, then you might also have to try setting the value of the XAUTHORITY environment variable to the value found in the environment of the user's interactive processes, which could be extracted using the psutil package, but let's hope this isn't needed.

Python script autorun on windows startup

I am trying to create a script that will display a page in chrome on startup. That is, I am trying to run a python script on startup. I am using the winreg module to do so.
Here is my script to add a my page display script on startup:
import winreg
import os
import sys, traceback
def AddToRegistry():
pth = os.path.dirname(os.path.realpath(path_to_page_display_script))
s_name="test.py"
address=os.path.join(pth,s_name)
try:
open = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\\Microsoft\\Windows\\CurrentVersion\\Run", reserved=0, access = winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(open,"pytest",0,winreg.REG_SZ,address)
winreg.CloseKey(open)
except Exception:
traceback.print_exc(file=sys.stdout)
if __name__=="__main__":
AddToRegistry()
Here is my page display script:
import webbrowser
url = 'http://docs.python.org/'
chrome_path = 'path_to_chrome/chrome.exe %s'
webbrowser.get(chrome_path).open(url)
The script runs fine without any errors but on restarting my machine, the chrome does not open up by itself nor does it display the page. Basically, my script does not run. What is wrong ? Kindly help me out.
The problem isn't with your script. It's with your registry key.
You need to tell windows to invoke Python.exe C:\path_to_script\test.py, not test.py.
So instead of this:
This:
path_to_python_exe = "C:\\python\\python38";
address=os.path.join(pth,s_name)
address = os.path.join(path_to_python_exe, "python.exe") + " " + address;
Or if Python.exe is guaranteed to be in your PATH, simply this:
address = "Python.exe" + " " + os.path.join(pth,s_name)

iwconfig unavailable to processes started with crontab #reboot?

this is my first post to stackoverflow, so please bear with me :)
I'm trying to read the output of iwconfig from a python script to determine whether there is a wifi connection. When I run script (via a bash script that first sets the directory) using crontab #reboot (user, not root), subprocess.check_output(['iwconfig']) always throws an [Errno 2]. This is even true when I catch the error using try/except and loop the code, so it is still running when the Wifi is certainly connected (as I can check with running iwconfig manually). When I run the python script from the command line via the same bash script, it works fine. What am I overlooking?
#!/usr/bin/python3
import subprocess
import time
import logging
logging.basicConfig(filename='wifi_check.log', filemode='w', format='%(name)s - %(levelname)s
- %(message)s', level=logging.DEBUG)
logging.info("Checking for Wifi")
for i in range(20):
try:
iwconfig_output = subprocess.check_output(['iwconfig']).decode('utf-8')
except Exception as err:
logging.error(str(i) + str(err))
else:
logging.debug(str(i) + iwconfig_output)
if "ESSID" in iwconfig_output:
logging.info(str(i) + "Wifi active")
time.sleep(10)
Errno 2 can indicate that the file is not found.
Perhaps iwconfig is not in PATH for the user who executes the script. Try using /sbin/iwconfig (the full path) of the executable to rule this out.

Can't run the shell command through html form using python cgi

I want to copy the folder from one server to another by executing the following shell command
sshpass -p 'XXXX' scp -r root#X.X.X.X(ip): Sourcedirectory(sdr) DestinationDirectory(ddr) ,
using the python script and web GUI.
I have html form page with 3 inputs (ip,sdr,ddr), when I pass these inputs through web page to the python script these inputs are copied to their respective location , but the command is not being executed and rest of the lines in python file gets executed.
if the same script is executed by command line it works.
Can anyone help me where Im missing out.
The following is the code I used.
Python script:
#!/usr/bin/python
import gzip,glob,os.path
import os
import subprocess
# Import modules for CGI handling
import cgi, cgitb
import time
# Create instance of FieldStorage
# Get data from fields
form = cgi.FieldStorage()
ip = form.getvalue('ip')
sdr = form.getvalue('sdr')
ddr = form.getvalue('ddr')
import sys
class RunCmd(object):
def cmd_run(self, cmd):
self.cmd = cmd
subprocess.call(self.cmd, shell=True)
id=("sshpass -p 'XXXX' scp -r root#%s:%s %s" %(ip,sdr,ddr))
b = RunCmd()
b.cmd_run(id)

Python - how to run the application and leave until it end?

How can i run the application and leave instead of waiting when it will be ended? for example : /var/tmp/runme.sh &
Following code is working but it waits forever when Google Chrome will exit. how can i run Google Chrome but let my script exit?
import subprocess
import sys
import time
line = sys.argv[1]
print line
def kill_chrome():
subprocess.call(['Taskkill', '/IM', 'chrome.exe', '/F'])
def run_chrome():
subprocess.call(['C:/Program Files (x86)/Google/Chrome/Application/chrome.exe', '--kiosk'])
def run_java():
subprocess.call(['java', '-cp', 'C:/Python27/pdfbox-app-2.0.0-RC3.jar;C:/Python27/jprint.jar', 'JPrint'])
try:
if line.startswith("myjava:website"):
print "Google Chrome - IDLE"
run_chrome()
elif line.startswith("myjava:a4"):
print "Printing - JAVA"
run_java()
elif line.startswith("myjava:kill"):
print "Killer"
kill_chrome()
except Exception, err:
print (err)
pass
#time.sleep(2)
What about subprocess.Popen? Looks like it does exactly what you want - runs app end does not waiting. You also pass arguments to the runned application.
from subprocess import Popen
Popen( [ "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", "myarg"])
Without "myarg" it works too.

Categories

Resources