使用在Raspberry Pi上的后台运行的python脚本创建文本文件(Creating a text file using a python script that runs in backgro

编程入门 行业动态 更新时间:2024-10-27 18:31:47
使用在Raspberry Pi上的后台运行的python脚本创建文本文件(Creating a text file using a python script that runs in background on Raspberry Pi)

我对标题中的主题有疑问。 我在目录/ home / pi /上创建了一个python脚本,当Raspberry Pi启动时,它开始在后台运行。 这是责任:

当我按下一个连接到其中一个GPIO的按钮时,它会在它自己的目录中创建一个文件夹,然后在目录/ home / pi /中创建一个名为'fileName.txt'的文本文件。 并在此文本文件中写入它刚刚创建的文件夹的名称。 一切顺利,直到“创建文本文件”部分。 我启动Raspberry Pi,然后按下按钮。 该脚本创建了我想要的文件夹,但之后,它不会创建文本文件。 由于它在后台运行,我无法在终端上看到可能解释问题的错误。 之后,我尝试手动启动脚本以查看错误消息; 然而,这次它运作得非常好。 它创建了文本文件并在其中写入了文件夹的名称。

这是我用来创建文件的简单代码:

text_file = open("folderName.txt", "w") text_file.write("%s" %folderName) text_file.close()

谁知道如何解决它?

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. 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/; 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. 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?

最满意答案

它可能是在错误的文件夹中创建文件。 尝试指定要在其中创建文件的绝对路径,或在脚本中发现它,如下例所示:

import os cwd = os.path.dirname(os.path.abspath(__file__)) text_file = open(os.path.join(cwd, "folderName", "textFile.txt"), "w")

此外,要测试在后台运行的脚本,您可以将调试消息写入/var/log的日志文件(可能需要root权限)或/tmp ,使用带有FileHandler的Logging module或使用open built -in功能。

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.

更多推荐

本文发布于:2023-07-27 15:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292446.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   脚本   后台   python   Pi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!