[英]Creating a text file using a python script that runs in background on Raspberry Pi
I'm having a problem about the topic in the title. 我在标题中遇到有关该主题的问题。 I created a python script on the directory /home/pi/ and it starts running on the background when the Raspberry Pi is booted.
我在目录/ home / pi /上创建了一个python脚本,当Raspberry Pi启动时,它开始在后台运行。 It's duty is this:
职责是这样的:
When I push a button that is connected to one of the GPIO's, it will create a folder in it's own directory, then create a text file called 'fileName.txt' at the directory /home/pi/; 当我按下一个连接到GPIO之一的按钮时,它将在其自己的目录中创建一个文件夹,然后在目录/ home / pi /中创建一个名为“ fileName.txt”的文本文件。 and write the name of the folder it just created, in this text file.
并在此文本文件中写入刚创建的文件夹的名称。 Everything goes fine until the 'create a text file' part.
一切正常,直到“创建文本文件”部分为止。 I boot the Raspberry Pi, then I push the button.
我启动Raspberry Pi,然后按一下按钮。 The script creates the folder that I want, but after that, it doesn't create the text file.
该脚本创建了我想要的文件夹,但是此后,它不再创建文本文件。 Since it runs in background, I can't see the error on the terminal that may explain the problem.
由于它在后台运行,因此在终端上看不到可能解释该问题的错误。 After that, I tried starting the script manually to see the error message;
之后,我尝试手动启动脚本以查看错误消息。 however, this time it worked perfectly well.
但是,这次它运行良好。 It created the text file and wrote the name of the folder in it.
它创建了文本文件,并在其中写入了文件夹的名称。
This is the simple code that I use to create the file: 这是我用来创建文件的简单代码:
text_file = open("folderName.txt", "w")
text_file.write("%s" %folderName)
text_file.close()
Anyone knows how to solve it? 有人知道如何解决吗?
It is probably creating the file in the wrong folder. 可能是在错误的文件夹中创建了文件。 Try specifying the absolute path where you want to create the file, or discover it inside the script, like the example below:
尝试指定要在其中创建文件的绝对路径,或在脚本内发现它,如以下示例所示:
import os
cwd = os.path.dirname(os.path.abspath(__file__))
text_file = open(os.path.join(cwd, "folderName", "textFile.txt"), "w")
Also, to test a script that is running in background, you can write debug messages to a log file in /var/log
(might need root permission) or /tmp
, either using the Logging module
with a FileHandler
, or using the open
built-in function. 另外,要测试在后台运行的脚本,您可以将
Logging module
与FileHandler
一起FileHandler
,也可以将open
内置的调试消息写入/var/log
(可能需要root权限)或/tmp
的日志文件中。入功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.