據我所知,你有幾個設備在com
端口,你想選擇其中的一個,並將該端口分配給VARIABLE
。
以下代碼讀取COM
端口並將第一個端口指定爲可用的COM端口。然後它會探測端口COM
,看它是否打開。
您可以檢查serial_ports()
輸出以確定要使用和相應的端口slice
分配相應地VARIABLE
這COM PORT
。我用port 0
這是我的COM1
功能serial_ports()
是跨平臺的。我有窗戶,它可以無縫工作。從here
演示代碼
import sys
import glob
import serial
def serial_ports():
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
if __name__ == '__main__':
VARIABLE = serial_ports()[0] #Assign first port as COM port
ser = serial.Serial(
port=VARIABLE,
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
print "Is port", VARIABLE , " open ?", ser.isOpen()
輸出
靈感
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Is port COM1 open ? True
>>>
感謝工作吧! – karmax