如何确定哪对伪tty端口相互连接 [英] How to determine which pair of pseudo tty ports are connected to each other
问题描述
我有两个python程序,它们通过点对点tty串行连接相互通信.为了模拟连接,我使用socat创建一个双向字节流,如下所示:
I have two python programs that are to communicate with each other over a point to point tty serial connection. To simulate the connection, I create a bi-directional byte stream using socat as here:
socat -d -d pty,raw,echo=0 pty,raw,echo=0
控制台将返回以下内容,指示现在已连接在一起的两个pty端口:
The console returns the following, indicating the two pty ports that are now connected together:
2018/04/15 22:33:03 socat[18197] N PTY is /dev/pts/2
2018/04/15 22:33:03 socat[18197] N PTY is /dev/pts/3
2018/04/15 22:33:03 socat[18197] N starting data transfer loop with FDs [5,5] and [7,7]
然后,我必须手动修改两个程序中的每个程序,以为每个程序指定串行连接,例如:
Then I have to modify each of the two programs manually to specify the serial connection for each, such as:
在程序A.py中:
import serial
...
ser = serial.Serial('/dev/pts/2')
在程序B.py中:
import serial
...
ser = serial.Serial('/dev/pts/3')
我想要的是一个脚本,该脚本将建立socat连接,然后使用一个作为参数传递给它的端口号执行A.py,并使用另一个作为参数传递给它的端口号执行B.py.论点.
What I'd like is a script that would set up the socat connection, then execute A.py with one port number passed to it as an argument, and execute B.py with the other port number passed to it as an argument.
我已经尝试过bash脚本,但是socat
命令会阻塞,并且我无法捕获其stderr输出以将其放入变量中.如果可以的话,我可以解析该变量并以自己的方式进行.
I've tried a bash script, but the socat
command blocks and I can't capture its stderr output to put it in a variable. If I could, I could then parse the variable and be on my merry way.
有什么想法吗?或者,也许是一种更好的方法呢?
Any ideas? Or maybe a muy better way to do this?
谢谢!
推荐答案
您可以使用python中的低级Popen
类运行socat
而不会阻塞.您需要重定向stderr
,以便可以扫描它的pty名称,但是在获取所需信息之后,可以将其传递给后台线程.
You can run socat
without blocking using the low level Popen
class in python. You need to redirect stderr
so that you can scan it for the pty name, but then you can hand it off to a background thread after you get the information you want.
import sys
import subprocess as subp
import threading
import shutil
import re
socat_proc = subp.Popen(['socat', '-d', '-d', 'pty,raw,echo=0', 'pty,raw,echo=0'],
stderr=subp.PIPE)
try:
# scan output for 2 ptys
ptylist = []
for line in socat_proc.stderr:
line = line.decode().strip()
print(line)
pty = re.search(r"N PTY is (.+)", line)
if pty:
ptylist.append(pty.group(1))
if len(ptylist) == 2:
break
if socat_proc.poll() is not None:
print("badness. socat dead.")
exit(2)
# background thread consumes proc pipe and sends to stdout
socat_thread = threading.Thread(target=shutil.copyfileobj,
args=(socat_proc.stdout, sys.stdout))
socat_thread.daemon = True
socat_thread.start()
print("pty", ptylist)
# now you can start your programs...
finally:
socat_proc.terminate()
这篇关于如何确定哪对伪tty端口相互连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!