开发者

how to read command output from serial device using python

I have an embedded linux device and here's what I would like to do using python:

  1. Get the device console over serial port. I can do it like this:

    >>> ser = serial.Serial('/dev/ttyUSB-17', 11开发者_运维知识库5200, timeout=1)

  2. Now I want to run a tail command on the embedded device command line, like this:

    # tail -f /var/log/messages

and capture the o/p and display on my python >>> console.

How do I do that ?


Just open the file inside python and keep readign from it. If needed be, in another thread:

>>> ser = serial.Serial('/dev/ttyUSB-17', 115200, timeout=1)
>>> output = open("/var/log/messages", "rb")

And inside any program loop, just do:

data = output.read()
print(data)

If you want it to just go printing on the console as you keep doing other stuff, type in something like:

from time import sleep
from threading import Thread
class Display(Thread):
    def run(self):
        while True:
            data = self.output.read()
            if data: print(data)
            sleep(1)


t = Display()
t.output = output
t.start()


very first you need to get log-in into the device. then you can run the specified command on that device. note:command which you are going to run must be supported by that device.

Now after opening a serial port using open() you need to find the login prompt using Read() and then write the username using write(), same thing repeat for password.

once you have logged-in you can now run the commands you needed to execute

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜