python实现控制COM口的示例

yipeiwu_com6年前Python基础

使用RS232串口线或者是RS232转USB的这一类的接口,会需要com口作为接口来进行输入输出调式,

写了个脚本来控制COM口,用到了Python内建的serial库

代码如下:

# coding=utf-8
 
import serial
import time
 
def setTout(t):
  print "Old Timeout is:[%s]" % po1.getTimeout() 
  po1.setTimeout(t)
  print "New Timeout is:[%s]" % po1.getTimeout() 
 
def sendShell(sp,cmd):
  sp.write(cmd+"\n")
  print "send shell cmd:[%s]" % cmd
  str = sp.readall()
  return str
 
def shell_io(sp,cmd,sleepTime):
  str = sendShell(sp,cmd) 
  print str
  time.sleep(sleepTime)
  
po1 = serial.Serial('com1',115200) 
timeStart = time.time() 
portnow = po1.portstr     
print "COM port now is:[%s]" % portnow
setTout(5)
 
shell_io(po1,"ls",2)
 
shell_io(po1,"pwd",2)
 
shell_io(po1,"ls -l",2)
 
po1.close()
 

以上这篇python实现控制COM口的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在Python中移动目录结构的方法

来源:http://stackoverflow.com/questions/3806562/ways-to-move-up-and-down-the-dir-structure-in-p...

Python的string模块中的Template类字符串模板用法

string.Template() string.Template()内添加替换的字符, 使用"$"符号, 或 在字符串内, 使用"${}"; 调用时使用string.substitut...

CentOS中升级Python版本的方法详解

CentOS升级Python2.6到Pythno2.7 最近在Linode上弄Python、出现ValueError: zero length field name in format这...

Python打开文件、文件读写操作、with方式、文件常用函数实例分析

Python打开文件、文件读写操作、with方式、文件常用函数实例分析

本文实例讲述了Python打开文件、文件读写操作、with方式、文件常用函数。分享给大家供大家参考,具体如下: 打开文件: 在python3中,打开文件的函数是: open(file,...

Pytorch释放显存占用方式

如果在python内调用pytorch有可能显存和GPU占用不会被自动释放,此时需要加入如下代码 torch.cuda.empty_cache() 我们来看一下官方文档的说明 Relea...