Linux 和 Python:自动检测 Arduino 串口 [英] Linux and Python: auto-detect Arduino serial port
问题描述
我在使用 Mac/Linux 用 Python 自动检测我的 Arduino 串行端口时遇到问题.
I have a problem automagically detecting my Arduino's serial port in Python, using Mac/Linux.
我知道一个可用的 shell 命令来查找端口;因为Arduino串口几乎总是以tty.usbmodem
开头,你可以用ls/dev | 找到串口.grep tty.usbmodem
应该返回类似 tty.usbmodem262141
的东西.
I know a working shell command to find the port; because Arduino serial ports almost always begin with tty.usbmodem
, you can find the serial port with ls /dev | grep tty.usbmodem
which should return something like tty.usbmodem262141
.
然而,我对如何从我的 Python 代码调用这个 shell 命令感到困惑.我试过这个:
However, I'm confused on how to call this shell command from my Python code. I've tried this:
p = "/dev/" + str(subprocess.Popen('ls /dev | grep tty.usbmodem', shell=True).stdout)
这应该使 p
成为 /dev/tty.usbmodem262141
.
然而,目前我得到 /dev/None
.
如何修改我的 shell 脚本调用以返回正确的字符串?我尝试使用 几个命令来调用 shell 脚本,但是没有一个工作.
How can I modify my shell script call to return the right string? I've tried to use several commands to call shell scripts, but none have worked.
推荐答案
首先,如果你使用的是 shell,你可以使用 glob (*
),这样你的命令就会变成ls/dev/tty.usbmodem*
.
First of all, if you're using a shell, you can use a glob (*
), so your command would become ls /dev/tty.usbmodem*
.
接下来,您甚至无需调用 shell 命令即可在 Python 中使用 glob!
Next, you don't even have to call a shell command to use a glob in Python!
考虑以下代码:
import glob
print(glob.glob("/dev/tty.usbmodem*"))
这篇关于Linux 和 Python:自动检测 Arduino 串口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!