繁体   English   中英

通过cron运行时,为什么我的Python脚本没有打开文本文件?

[英]Why doesn't my Python script open a text file when run via cron?

我有一个Python程序,当我从LXTerminal正常运行该程序时,它可以正常运行:

$ sudo python testcon.py

但是当我使用cron运行它以在重新启动后启动时:

@reboot python /home/pi/testcon.py &

它停在行:

f = open('info.txt')

并且什么也不会做。 应该打开文件/home/pi/info.txt

为什么会这样? 我怎样才能解决这个问题?

这是显示问题的程序的简单版本:

import smbus
import time

bus = smbus.SMBus(1) # Rev 2 Pi uses 1

DEVICE = 0x23 # Device address (A0-A2)
IODIRA = 0x00 # Pin direction register
OLATA  = 0x14 # Register for outputs
GPIOA  = 0x12 # Register for inputs

bus.write_byte_data(DEVICE,IODIRA,0x00)

bus.write_byte_data(DEVICE,OLATA,0xFF)  #set all of the outputs
time.sleep(3)                           #wait for 3 sec

f = open('info.txt')                    #should open the txt file
bus.write_byte_data(DEVICE,OLATA,0)     #clear all of the outputs
f.close()

@reboot选项只能在root用户中使用。 无法在用户的cron中调用它。 但是,有时它取决于您的操作系统。 这里

看着这个相当相似的问题 ,尤其是这个答案 ,我有两个建议:

a)树莓完全支持@reboot语法吗? 请阅读手册页中的cron和crontab进行检查。

b)从链接的答案看来,您需要添加应该执行脚本的用户的名称:

@reboot username /usr/bin/python /home/pi/test.py &

如果该程序仅在以root root身份运行时才能成功,请使用root作为用户名; 但是否则,避免以root用户身份运行始终是个好主意。

暂无
暂无

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

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