I know that I can use e.g. pySerial to talk to serial devices, but what if I don't have a device right now but still need to write a client for it? How can I write a "virtual serial device" in Python and have pySerial talk to it, like I would, say, run a local web server? Maybe I'm just not searching well, but I've been unable to find any information on this topic.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
this is something I did and worked out for me so far:
If you create more virtual ports you will have no problems as the different masters get different file descriptors even if they have the same name.
It may be easier to using something like com0com (if you're on Windows) to set up a virtual serial port, and develop on that.
Maybe a loop device will do the job if you need to test your application without access to a device. It's included in pySerial 2.5 https://pythonhosted.org/pyserial/url_handlers.html#loop
I was able to emulate an arbitrary serial port
./foo
using this code:SerialEmulator.py
socat
needs to be installed (sudo apt-get install socat
), as well as thepyserial
python package (pip install pyserial
).Open the python interpreter and import SerialEmulator:
Your client program can then wrap
./ttyclient
with pyserial, creating the virtual serial port. You could also make client_port/dev/ttyUSB0
or similar if you can't modify client code, but might needsudo
.Also be aware of this issue: Pyserial does not play well with virtual port
It depends a bit on what you're trying to accomplish now...
You could wrap access to the serial port in a class and write an implementation to use socket I/O or file I/O. Then write your serial I/O class to use the same interface and plug it in when the device is available. (This is actually a good design for testing functionality without requiring external hardware.)
Or, if you are going to use the serial port for a command line interface, you could use stdin/stdout.
Or, there's this other answer about virtual serial devices for linux.
If you are running Linux you can use the socat command for this, like so:
When the command runs, it will inform you of which serial ports it has created. On my machine this looks like:
Now I can write to
/dev/pts/13
and receive on/dev/pts/12
, and vice versa.