如何用python / c程序替换“ cat”和“ echo”读/写命令?

时间:2019-02-01 12:18:55

标签: command-line python echo

我无法替换设备输入/输出命令,例如:

echo 100 > /dev/rtmotor_raw_l0   # output 100hz frequency
cat /dev/rtswitch0 # read switch state

输出问题(python)

我尝试用python替换该命令。

file = open('/dev/rtmotor_raw_l0','w')
file.write('100\n')            # I want output in this timing
file.close()                   # output reflected after closing file

问题是关闭文件后出现输出。 这是否意味着我每次想更改其值时都必须打开和关闭该设备?另外,将'w'更改为'a'无效。

输入问题(python)

输入观察几乎发生同样的问题。

file = open('/dev/rtswitch','r')
file.read()  # works
file.read()  # after first read it does't work anymore
file.close() # need to reopen the file to get newer value

在每个打开的文件中我只能读取1个输入。

因此,目前每次要写入/读取新值时,我都必须重新打开设备。 有什么办法可以避免这个问题?

谢谢。

1 个答案:

答案 0 :(得分:1)

尝试在file.flush()通话后致电write()。它将缓冲区刷新到文件,您可以读取数据。