简体   繁体   English

如何将交互式Python脚本作为cron作业运行?

[英]How to run an interactive Python script as cron job?

I have a Python script, say test.py which interacts with the user everytime it is executed. 我有一个Python脚本,例如test.py ,它每次执行时都会与用户交互。

test.py test.py

#!/usr/bin/env python3

def foo():
    a = input()
    print("Hello, {}".format(a))

if __name__ == '__main__':
    foo()

I want to run this script every 5 minutes. 我想每5分钟运行一次此脚本。 So, I tried adding it to my crontab but it seems that this doesn't work as I am not prompted to enter an input. 因此,我尝试将其添加到我的crontab但是由于没有提示我输入内容,因此这似乎不起作用。
I have tested my crontab and it is working fine. 我已经测试了我的crontab ,并且工作正常。

Should I use libraries such as schedule for this task? 我应该使用诸如schedule库来schedule此任务吗?
What would be the ideal way of going about in this scenario? 在这种情况下,理想的做法是什么?
NOTE: I want a cross platform solution which works on MacOSX and GNU/Linux. 注意:我想要一个跨平台的解决方案,该解决方案可以在MacOSX和GNU / Linux上运行。

Your could try the python module pexpect ( http://pexpect.sourceforge.net/doc/ ) -- the usage is something like : 您可以尝试python模块pexpect( http://pexpect.sourceforge.net/doc/ )-用法类似于:

import pexpect
child = pexpect.spawn(script/python file etc...)
child.expect('Here goes the prompt you would expect')
child.sendline('What you want to send to it')

its not possible to have cron interact interactively on your server. cron无法在您的服务器上进行交互交互。

Delink your application: Setup a db (like MySQL), have test.py run via cron every 5 mins to check if a new entry is made in the db: then, have a local application that saves user prompt information to your db. 断开应用程序的链接:设置一个数据库(如MySQL),每5分钟通过cron运行一次test.py来检查是否在数据库中进行了新输入:然后,有一个本地应用程序将用户提示信息保存到您的数据库中。

If it is running via cron or schedule, it will not be running on your terminal, it will run as a background process. 如果它是通过cron或schedule运行的,则它将不会在您的终端上运行,它将作为后台进程运行。 Therefore, it cannot be interactive and you will not be prompted. 因此,它不能是交互式的,并且不会提示您。

If you just want to put a delay of 5 minutes, have you looked at the Linux "sleep" command or using python's "time.sleep"? 如果只想延迟5分钟,您是否看过Linux的“ sleep”命令或使用python的“ time.sleep”? In this way you can keep a terminal open and just have the job run in intervals. 这样,您可以使终端保持打开状态,并使作业间隔运行。

To keep it simple: 为简单起见:

#!/usr/bin/env python3
import time

def foo():
    a = input()
    print("Hello, {}".format(a))

if __name__ == '__main__':
    while True:
        foo()
        time.sleep(300) # Sleeps 300 seconds

You can get a script and use that in the crontab: 您可以获取脚本并在crontab中使用该脚本:

#!/bin/bash
/usr/bin/python3 /home/user/project/test.py << EOF
some input here
EOF

Your crontab will look like 您的crontab看起来像

* *  * * *   /home/user/project/test.sh >>  /home/user/project/LOG 2>&1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM