简体   繁体   English

在 Python 3.8 中运行 Crontab 时出现 SyntaxError invalid syntax

[英]SyntaxError invalid syntax when running Crontab in Python 3.8

I'm a newbie at this.我是这方面的新手。 I'm trying to use Crontab to periodically run a python script to control a stepper motor.我正在尝试使用 Crontab 定期运行 python 脚本来控制步进电机。 When I run 'stepper_motor_cron.py' in terminal,I keep getting the SyntaxError below.当我在终端中运行“stepper_motor_cron.py”时,我不断收到下面的 SyntaxError。


    File "stepper_motor_cron.py", line 4
        * * * * * cd /bleary83/Documents example1.py
          ^
    SyntaxError: invalid syntax

I'm practicing use of Crontab with the 'example1.py' script below.我正在练习使用 Crontab 和下面的“example1.py”脚本。 I believe the problem is in designating where the file 'example1.py' is located in the Crontab script.我认为问题在于指定文件“example1.py”在 Crontab 脚本中的位置。 I've tried many variations in the path but invariably come up with the syntax error message.我已经尝试了多种路径变体,但总是会出现语法错误消息。

I can run the 'example1.py' in terminal and I get the correct info in the 'append.txt' file.我可以在终端中运行“example1.py”,并在“append.txt”文件中获得正确的信息。

I've found crontab in the usr/bin directory.我在 usr/bin 目录中找到了 crontab。

#! /usr/bin
from crontab import CronTab
cron = CronTab()
* * * * * cd /bleary83/Documents example1.py

The following is the 'example1.py' script I'm trying to run to learn how crontab works.以下是我试图运行以了解 crontab 工作原理的“example1.py”脚本。 Once I learn how crontab works, I'll try to use it to schedule running the script I have to run the stepper motor using a Rasberry Pi contoller.一旦我了解了 crontab 的工作原理,我将尝试使用它来安排运行脚本,我必须使用 Rasberry Pi 控制器来运行步进电机。

from datetime import datetime
myFile = open('append.txt', 'a') 
myFile.write('\nAccessed on ' + str(datetime.now()))

You can't just randomly drop crontab syntax into a Python file and expect it to work.您不能只是随机地将 crontab 语法放入 Python 文件中并期望它起作用。 You should read the readme for python-crontab to actually see how to use it.您应该阅读python-crontab自述文件以实际了解如何使用它。 If you had, you'd have seen that you have to set the tab argument of CronTab to your crontab expression:如果有的话,您会发现必须将CronTabtab参数设置为您的 crontab 表达式:

cron = CronTab(tab="""
  * * * * * cd /bleary83/Documents example1.py
""")

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

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