python - 打开后文件还没有准备好写入?

标签 python linux gpio file-access

我有以下代码:

#!/usr/bin/python

export = open('/sys/class/gpio/export', 'w')
export.write('44\n')

此代码产生以下输出:

close failed in file object destructor:
IOError: [Errno 16] Device or resource busy

如果我通过在末尾添加 export.close() 来更改代码,我将得到以下输出:

Traceback (most recent call last):
  File "./test.py", line 5, in <module>
    export.close()
IOError: [Errno 16] Device or resource busy

但是,如果我再次这样更改代码,它会完美运行:

#!/usr/bin/python
from time import sleep

export = open('/sys/class/gpio/export', 'w')
sleep(1)
export.write('44\n')

请注意,.close 总是会失败,即使我在写入后长时间休眠也是如此。

编辑:

将我的代码更改为以下内容:

with open('/sys/class/gpio/export', 'w') as export:
    sleep(1)
    export.write('44\n')
    export.flush()
    export.close()

仍然报错:

Traceback (most recent call last):
  File "./test.py", line 7, in <module>
    export.flush()
IOError: [Errno 16] Device or resource busy

编辑 2:

我的主要问题原来是您无法导出已经导出的 GPIO。我已将我的代码更新为如下所示,它似乎可以正常工作:

from os import path

if not path.isdir('/sys/class/gpio/gpio44'):
    with open('/sys/class/gpio/export', 'w') as export:
        export.write('44\n')

if path.exists('/sys/class/gpio/gpio44/direction'):
    with open('/sys/class/gpio/gpio44/direction', 'w') as gpio44_dir:
        gpio44_dir.write('out\n')

if path.exists('/sys/class/gpio/gpio44/value'):
    with open('/sys/class/gpio/gpio44/value', 'w') as gpio44_val:
        gpio44_val.write('1\n')

此代码成功导出一个 GPIO,将其方向设置为“out”,并将其激活(值为 1)。

最佳答案

我的主要问题原来是您无法导出已经导出的 GPIO。我已将我的代码更新为如下所示,它似乎可以正常工作:

from os import path

if not path.isdir('/sys/class/gpio/gpio44'):
    with open('/sys/class/gpio/export', 'w') as export:
        export.write('44\n')

if path.exists('/sys/class/gpio/gpio44/direction'):
    with open('/sys/class/gpio/gpio44/direction', 'w') as gpio44_dir:
        gpio44_dir.write('out\n')

if path.exists('/sys/class/gpio/gpio44/value'):
    with open('/sys/class/gpio/gpio44/value', 'w') as gpio44_val:
        gpio44_val.write('1\n')

此代码成功导出一个 GPIO,将其方向设置为“out”,并将其激活(值为 1)。

关于python - 打开后文件还没有准备好写入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33828519/

相关文章:

linux - shell脚本停止错误

go - 不能在 strconv.ParseFloat 问题的参数中使用 (type []byte) 作为类型字符串

python - 将 numpy 标量转换为 python 简单 native (稍作改动)

Python:查找 URL 并添加查询字符串对

linux - 在日志文件中查找间隔

PHP 扩展在 LINUX 中不工作

python - 树莓派上的多个热电偶

embedded - u-boot根据GPIO状态选择启动分区

python - 如何裁剪图像中红点周围的固定补丁

python - pyparsing如何使用infixNotation来表示iif(cond, if true, if false)