Here is my script(randombg.py):
#!/usr/bin/env python
# -*- coding: utf8 -*-
import random
import subprocess
import os
BACKGROUND = '/home/david/wallpaper/dell2312'
IGNORE_FILES = ['/home/david/wallpaper/dell2312/.directory']
def enumerate():
global BACKGROUND
file_collections = []
for root, dirs, files in os.walk(BACKGROUND):
for file in files:
file_collections.append(os.path.join(root, file))
return file_collections
def randombg():
select_files = list(set(enumerate())-set(IGNORE_FILES))
subprocess.call(['feh', '--bg-scale', random.choice(select_files)])
def main():
while 1:
randombg()
if __name__ == '__main__':
main()
I have run chmod a+x randombg.py and it worked with python randombg.py .Let's say its path is /path/to/randombg.py. Also, run /path/to/randombg.py worked.
However, when I added it to crontab as below:
1 * * * * /path/to/randombg.py
or
01 * * * * python /path/to/randombg.py
or
01 * * * * /usr/bin/python /path/to/randombg.py
All failed.
I can't figure out. Could anyone explain?
PS: ArchLinux
More infomation
When I run ps aux|grep python, I can't find the randombg.py while sometimes it appears.
Addtional logs from crontab redirect stderr:
import: unable to open X server `' # error/import.c/ImportImageCommand/361.
import: unable to open X server `' # error/import.c/ImportImageCommand/361.
import: unable to open X server `' # error/import.c/ImportImageCommand/361.
/home/david/dotfiles/randombg.py: line 9: BACKGROUND: command not found
/home/david/dotfiles/randombg.py: line 10: IGNORE_FILES: command not found
/home/david/dotfiles/randombg.py: line 13: syntax error near unexpected token `('
/home/david/dotfiles/randombg.py: line 13: ` def enumerate():'
Try to change your subprocess.call to
subprocess.call("export DISPLAY=:0; feh --bg-scale " + random.choice(select_files), shell=True)
This should export the DISPLAY variable, as scripts run from crontab do not have access to environmental variables by default.
Related
I have a very simple test python script as seen below. This script sits on my Digital Ocean droplet.
#!/usr/bin/env python
import datetime
import time
def main():
f = open('output.txt','a')
f.write("Hello World! # :" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " --> _the_finish_\n")
print("Hello World! # :" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " --> _the_finish_\n")
f.close
if __name__ == '__main__':
for i in range(2):
main()
time.sleep(5)
I want this script to execute automatically using crontab. My crontab execution line is the following:
48 15 * * * /usr/bin/python3 /root/test_script/systemtime.py >> /tmp/systemtime.log 2>&1
The trouble I'm having is finding where or how to locate the python3 path in my Digital Ocean droplet, 1) where can I find or locate this python path I'm supposed to use? I don't have a tmp file in my Digital Ocean droplet, 2) so where will the .log file be stored? How can I configure the path for where the output will be stored?
Thanks all.
A way to find the Python path is running whereis python3. First make sure that it is installed.
It won't be stored. You should change /tmp/systemtime.log to your desired path. For instance, /root/test_script/test_script.log.
Btw, if you are using python3 you may want to change your shebang to #!/usr/bin/env python3.
I have seen a few question asking how to make a Python script that makes a beep sound.
This question is not about that.
When I run certain Python scripts Windows 7 makes a beep sound but I want to stop the beep.. or at least understand why it's happening.
Here is a test script - test.py:
#!/usr/bin/python
# importing modules
import os
import time
import datetime
from datetime import datetime
def f_log(strtext):
# In this method try and write to the log file
logFilePath = '/home/osmc/python/pyscripter_file.txt'
ts_local = datetime.now()
ts = ts_local.strftime("%d/%b/%Y %H:%M:%S")
try:
# Check if the logfile exists
if(os.path.isfile(logFilePath)):
# Append the error message to the log file. 'a+' creates the file if it does not exist.
with open(logFilePath, 'a+') as f:
f.write(ts + '\t' + strtext + '\n')
else:
print("Log File does not exist - Creating File now")
with open(logFilePath, 'a+') as f:
f.write(ts + '\t' + 'Log File does not exist - Creating File now' + '\n')
f.write(ts + '\t' + strtext + '\n')
except IOError as e:
# Handle the exception
print("Error Msg")
f_log("Test Script")
print("Hello World")
This script is in a directory on a Raspberry Pi running OSMC... in a folder called /home/osmc/python
I have opened it as a remote file in the Pyscripter IDE and can see ssh://osmc//home/osmc/python/test.py
So this means, the Pyscripter IDE, running on Windows 7, is running the Python script on the remote machine. When I run the script this way I get a beep when it finishes executing.
If I create a crontab to run it in osmc...
PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/bin/python
53 22 * * * /usr/bin/python /home/osmc/python/test.py >> out.txt 2>&1
Then the script also gives a beep at the end of execution.
If I run the script from a command line to osmc (from an ssh connection in Putty)
# cd /home/osmc/python
# python test.py
I DO NOT get a beep when it completes.
If I run this next script in Pyscripter (or any other way) it does NOT make a beep.
import sys
print('Python '+sys.version.replace('\n','')+' at '+sys.executable+' on '+sys.platform)
Why do I sometimes get the beep? Something in the Python code in the first script I guess?
Flex
My test Python script writes to a log file. I had that log file open in PyScripter IDE.
PyScripter IDE by design makes a beep to signal a File Change Notification affecting any files open in the IDE. This is what was causing the beep whether I was running the script from within PyScripter or not I was still getting the beep because the script was writing to the file open in PyScripter IDE.
I asked the developer and it is currently not possible to turn off this beep.
Flex
I'm a beginner trying to write a small Python script that I will run through Cron, but I'm getting a Syntax Error from my Cron output log about the program, although the script works fine running through Terminal.
File "/home/pi/Selenium.py", line 19
clickinput = driver.find_element_by_link_text(f"{date}- File")
^
SyntaxError: invalid syntax
I tried looking up how to do this, and one person with a similar issue changed Cron to run as Bash instead of sh, but when I added SHELL = /bin/bash to the Cron file, nothing happened, and I got the same error. Additionally, when I change the f-string into a non f-string, a "selenium module not found" error gets thrown instead.
Any help figuring out the cause of the error would be appreciated!
Cron command:
PATH = /home/pi/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/s$
SHELL = /bin/bash
20 18 * * * /home/pi/Selenium.py > /home/pi/Desktop/backdown.log 2>&1
20 18 * * * env > /home/pi/Desktop/env.output 2>&1
Here is my Python script (minus private info)
#!/usr/bin/env python
import time
from datetime import datetime
from selenium import webdriver
driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver")
driver.get("website");
searchinput = driver.find_element_by_name('mail')
searchinput.send_keys("email")
searchinput = driver.find_element_by_name("pass")
searchinput.send_keys("password")
searchinput.submit()
date = datetime.today().strftime("%m/%d")
if date.find("0") == 0:
date = date.lstrip("0")
clickinput = driver.find_element_by_link_text(f"{date}- File")
clickinput.click()
(This is my first time posting, so sorry if it's bad)
I set up a crontab file to execute a python file every minute however it states it executed but no file is generated.
crontest1.py file contains:
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
if __name__ == '__main__':
f = open('/APPS/CronRun/crontest/dummy1.txt','w')
f.write('hello world it is a file')
f.close()
Crontab file:
# /etc/crontab - root's crontab for FreeBSD
#
# $FreeBSD: release/10.0.0/etc/crontab 194170 2009-06-14 06:37:19Z brian $
#
SHELL=/bin/sh
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin
#
#minute hour mday month wday who command
#
* * * * * root /APPS/CronRun/crontest/crontest1.py
11 11 * * * root /usr/bin/find /APPS/* | grep python | grep core | xargs rm
14 14 17 * * root /APPS/CronRun/Report/report.py
The crontab executes but no file appears.
I tried a simple date >> datelog.txt
which works via crontab but the python file does not seem to execute.
The python file works if executed manually from the shell but not via crontab
I have tried explicitly stating: python /APPS/CronRun/crontest/crontest1.py in the crontab file, but this does not work
I have previously added cron jobs that work fine and still execute daily without any issues
e.g
31,01 * * * * root /APPS/CronRun/makelist/list.py
Try the code without :
if __name__ == '__main__':
Like this:
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
f = open('/APPS/CronRun/crontest/dummy1.txt','w')
f.write('hello world it is a file')
f.close()
Maybe " crontest1.py " is executed by crontab as a module - not "main".
If that doesn't help try to update the Python.
Python 3.1.x and lower
may be the reason.
I'm going to run a python script with a parameter using cronjob.
The parameter is password of database that needs to be used in the script.
#!/usr/bin/python
import MySQLdb
import requests
import json
import os
import sys
param=sys.argv
password=param[1]
db = MySQLdb.connect(host="host.com",port=3306,user="user",passwd=password,db="db")
/etc/crontab:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
# * * * * * user-name command to be executed
Crontab -e
*/5 * * * * /home/test/run.py "dbpass'"
which python:
/usr/bin/python
Error in /var/spool/mail
/bin/sh: dbpass': command not found
If I run the script manually, it works fine: python run.py "dbpass'"
Any help would be appreciated.
The string you posted contains unicode characters, it's representation is
u'*/5 * * * *\u2002\u2002/home/test/run.py "dbpass\'"'
# or encoded to utf-8:
b'*/5 * * * *\xe2\x80\x82\xe2\x80\x82/home/test/run.py "dbpass\'"'
\u2002 is EN SPACE
So the 5th argument is actually *\u2002\u2002/home/test/run.py which it seems cron treats like a *, taking the next item as the command.
So just replace those EN SPACE characters with normal spaces then it should work.
Your crontab entry should have the password without quotes:
*/5 * * * * /home/test/run.py dbpass