首页 > 解决方案 > 如何在 Ubuntu 20.04 中运行手动运行但不使用 CRON 的 Python Cron 作业?

问题描述

我正在尝试运行一个 python cron 脚本,它将批量转换目录中的所有视频文件。python 脚本基于 MoviePy,在手动触发时可以无缝运行。但是当在 Cron Job 中触发时,它没有按预期运行/工作。

我已经设置了一个 Shell 脚本,其中我保留了 Python 脚本以进行任何错误崩溃处理。我正在从 cron 调用 shell 脚本。

这是我的代码:

crontab -e:

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command
# * * * * * /usr/bin/python3 /var/www/html/cgi-bin/in.py /var/www/html/cgi-bin/log.txt
# * * * * * /bin/bash -c "/var/www/html/cgi-bin/cron.sh"
* * * * * cd /bin/bash /var/www/html/cgi-bin/cron.sh > /var/www/html/cgi-bin/log.txt 2> &1

Cron.sh 是 Cron 将运行的我的 Shell 文件。

#!/bin/sh
echo $(date) >> /var/www/html/cgi-bin/log.txt
/usr/bin/python3 /var/www/html/cgi-bin/in.py >>  /var/www/html/cgi-bin/log.txt

这是我的 Python 文件 - In.py:

import moviepy.editor as mp
import sys, getopt
import requests
from datetime import datetime
from random import randint
import os, os.path, random
import shutil






rand_aud = str(randint(0, len(os.listdir('aud/'))))


inputfile = ''
keypass = ''

def main(argv):
   inputfile = ''
   keypass = ''
   try:
      opts, args = getopt.getopt(argv,"hi:k:",["ifile=","key="])
   except getopt.GetoptError:
      print ('in.py -i <inputfile> -k <user_key>')
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print ('in.py -i <inputfile> -k <user_key>')
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-k", "--key"):
         keypass = arg
        
#    print(inputfile)
#    print(keypass)

directory = r'in/'
for filename in os.listdir(directory):
   inp = os.path.join(directory, filename)
   #if inp == '':
   #   inp = 'in/f.mp4'
   now = datetime.now()
   value = randint(0, 10)
   dt_stamp = now.strftime("%d%m%Y%H%M%S") + str(value)


   out = 'out/' + keypass + '_' + dt_stamp + '.webm'
   # aud = 'aud/' + rand_aud +'.WAV'
   aud = 'aud/' + random.choice(os.listdir("aud/"))
   print(out)
   logu = 'logo.png'


   video = mp.VideoFileClip(inp)
   # if video.rotation == 90:
   video = video.resize(video.size[::-1])
   video.rotation = 0


   logo = (mp.ImageClip(logu)
           .set_duration(video.duration)
           .resize(height=50) # if you need to resize...
           .margin(right=8, top=8, opacity=0) # (optional) logo-border padding
           .set_pos(("right","top")))

   if aud != '':
       audioclip = mp.AudioFileClip(aud).set_duration(video.duration)
       new_audioclip = mp.CompositeAudioClip([audioclip])
       video.audio = new_audioclip



   final = mp.CompositeVideoClip([video, logo])
   final.write_videofile(out)
   if os.path.exists(inp):
        os.remove(inp)

   url = 'https://get-data.worlds.com.au?Auth=SSSOSXSQSSSXSQSXSOSSSOSS&Sender_key=' + keypass + '&handle=stream_response'
   # print ('Posting Data To ' + url)

   userdata = {"loc": out, "stamp": dt_stamp, "Auth": keypass, "handle": "stream"}
   resp = requests.post(url)
   

#    files = {'file': open(out, 'rb')}
#    userdata = {"loc": out, "stamp": dt_stamp, "Auth": keypass, "handle": "stream"}
#    resp = requests.post(url, files=files, params=userdata)
#    r = requests.get(url, headers={"Auth":keypass, "handle":"stream"})

   # print ('Call Response:')
   # print (resp)

if __name__ == "__main__":
   main(sys.argv[1:])

这是 log.txt 文件。请注意,MoviePy Done 是我手动执行的。其余的是 CRON 调用。那些只有时间的显示 cron 作业正在运行,但 python 脚本不是:

Mon Apr 12 08:38:17 UTC 2021
out/_120420210838183.webm
Moviepy - Building video out/_120420210838183.webm.
MoviePy - Writing audio in _120420210838183TEMP_MPY_wvf_snd.ogg
MoviePy - Done.
Moviepy - Writing video out/_120420210838183.webm

Moviepy - Done !
Moviepy - video ready out/_120420210838183.webm
out/_120420210838374.webm
Moviepy - Building video out/_120420210838374.webm.
MoviePy - Writing audio in _120420210838374TEMP_MPY_wvf_snd.ogg
MoviePy - Done.
Moviepy - Writing video out/_120420210838374.webm

Moviepy - Done !
Moviepy - video ready out/_120420210838374.webm
Mon Apr 12 08:39:01 UTC 2021
Mon Apr 12 08:40:01 UTC 2021
Mon Apr 12 08:41:01 UTC 2021
Mon Apr 12 08:42:01 UTC 2021
Mon Apr 12 08:43:01 UTC 2021
Mon Apr 12 08:44:01 UTC 2021
Mon Apr 12 08:45:01 UTC 2021
Mon Apr 12 08:46:01 UTC 2021
Mon Apr 12 08:47:01 UTC 2021
Mon Apr 12 08:48:02 UTC 2021
Mon Apr 12 08:49:01 UTC 2021
Mon Apr 12 08:50:01 UTC 2021
Mon Apr 12 08:51:01 UTC 2021
Mon Apr 12 08:52:01 UTC 2021
Mon Apr 12 08:53:01 UTC 2021
Mon Apr 12 08:57:01 UTC 2021
Mon Apr 12 08:58:01 UTC 2021
Mon Apr 12 08:59:01 UTC 2021
Mon Apr 12 09:00:01 UTC 2021
Mon Apr 12 09:01:01 UTC 2021
Mon Apr 12 09:02:01 UTC 2021
Mon Apr 12 09:03:01 UTC 2021
Mon Apr 12 09:04:01 UTC 2021
Mon Apr 12 09:05:01 UTC 2021
Mon Apr 12 09:06:01 UTC 2021
Mon Apr 12 09:07:01 UTC 2021
Mon Apr 12 09:08:01 UTC 2021
Mon Apr 12 09:09:01 UTC 2021
Mon Apr 12 09:10:01 UTC 2021
Mon Apr 12 09:11:01 UTC 2021
Mon Apr 12 09:12:02 UTC 2021
Mon Apr 12 09:13:01 UTC 2021
Mon Apr 12 09:14:01 UTC 2021
Mon Apr 12 09:15:01 UTC 2021
Mon Apr 12 09:16:01 UTC 2021
Mon Apr 12 09:17:01 UTC 2021

标签: pythonlinuxshellcron

解决方案


推荐阅读