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

File not ready for write after open?

我有以下代码:

#!/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)。