为什么Python脚本在通过cron运行时不打开文本文件?

2024-09-28 01:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

$ sudo python testcon.py

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

^{pr2}$

它停在那条线上:

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()

Tags: theimport程序infotxtfordatadevice
2条回答

看看this rather similar question,尤其是{a2},我有两个建议:

a)raspberry是否支持@reboot语法?通过阅读cron和crontab的手册页进行检查。在

b)从linked answer看来,您需要添加应该执行脚本的用户的名称:

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

如果程序只有在以root身份运行时才能成功,请使用root作为用户名;否则最好不要以root身份运行。在

@reboot选项只能在根目录下使用。不能在用户的cron中调用它。但是,有时这取决于您的操作系统。见here。在

相关问题 更多 >

    热门问题