2016-02-15 225 views
4

我试图制作一个将写入文件的python循环脚本。在启动时执行时不写入文件的Python脚本

当我在终端执行脚本时,文件写入没有问题。

我不想在启动时启动这个脚本,所以我把它放在rc.local文件中。脚本运行,但它不写输出到指定的文件..

我做了一些阅读冲洗和无缓冲输出.. 任何人都可以帮助我或指出我在正确的方向吗?

当该脚本完成它会使用REST发送的文件,但我需要之前,我甚至那里写入文件..

脚本:

#!/usr/bin/python -u 

while True: 
    try: 
     print "This is only a test..." 
     with open("loop.txt", "a") as loopFile: 
      loopFile.write("This is only a test...") 
      loopFile.write('\n') 
      loopFile.flush() 
      loopFile.close() 
     time.sleep(1) 
    except KeyboardInterrupt: 
     break 
     quit() 

的/ etc/rc中.local文件:

/usr/bin/python /home/pi/loop.py & 

loop.py和loop.txt都具有读/写/执行权限。

+1

由于您使用'开放的()',你不需要'loopFile.close()' –

+1

这个脚本中几乎肯定运行与在终端上时不同的工作目录...打开文件时需要指定完整路径名称。 – gariepy

+1

这是因为操作系统为您运行它时文件“loop.txt”不存在。你需要指定完整路径 – Fredrik

回答

5

添加全路径名来声明打开文件:

#!/usr/bin/python -u 

while True: 
    try: 
     print "This is only a test..." 
     with open("/home/users/sj091190/loop.txt", "a") as loopFile: 
      loopFile.write("This is only a test...") 
      loopFile.write('\n') 
      loopFile.flush() 
     time.sleep(1) 
    except KeyboardInterrupt: 
     break 
     quit() 
+0

哇,那是一个快速编辑!干得好,@VincentSavard – gariepy

+0

这工作完美。谢谢! – sjo91190

+0

@ sjo91190:请参阅[_当某人回答我的问题时该怎么办?_](http://stackoverflow.com/help/someone-answers) – martineau

相关问题