A. python如何获取串口前面的名称
楼上的方法太复杂,用serial库就可以,亲测可用:
importserial.tools.list_ports
port_list=list(serial.tools.list_ports.comports())
iflen(port_list)==0:
print('找不到串口')
else:
foriinrange(0,len(port_list)):
print(port_list[i])
参考:网页链接
B. python里面的__int__怎么用
类在初始化的时候,就自动调用了。所以,你想要什么东西,在初始化的时候自动完成,就可以把这个玩意放在那里
C. java代码怎么写成PYTHON代码代码如下
这个做的就是把1952的每个数加起来吧,纳凳槐1+9+5+2,最后输出17。洞友
java的方粗做法:
int sumDigits=0;
for(char c:String.valueOf(1952).toCharArray())
sumDigits+=((int)c-48);
System.out.println(sumDigits);
D. python可以通过什么命令更改ip地址
#!/usr/bin/env python
#-*- encoding:gb2312 -*-
Filename: IP.py
import sitecustomize
import _winreg
import ConfigParser
from ctypes import *
print '正在进行网络适配器检测,请稍候…'
print
netCfgInstanceID = None
hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \
r'System\CurrentControlSet\Control\Class{4d36e972-e325-11ce-bfc1-08002be10318}')
keyInfo = _winreg.QueryInfoKey(hkey)
寻找网卡对应的适配器名称 netCfgInstanceID
for index in range(keyInfo[0]):
hSubKeyName = _winreg.EnumKey(hkey, index)
hSubKey = _winreg.OpenKey(hkey, hSubKeyName)
try:
hNdiInfKey = _winreg.OpenKey(hSubKey, r'Ndi\Interfaces')
lowerRange = _winreg.QueryValueEx(hNdiInfKey, 'LowerRange')
检查是否是以太网
if lowerRange[0] == 'ethernet':
driverDesc = _winreg.QueryValueEx(hSubKey, 'DriverDesc')[0]
print '检测到网络适配器名:', driverDesc
netCfgInstanceID = _winreg.QueryValueEx(hSubKey, 'NetCfgInstanceID')[0]
print '检测到网络适配器ID:', netCfgInstanceID
if netCfgInstanceID == None:
print '没有找到网络适配器,程序退出'
exit()
break
_winreg.CloseKey(hNdiInfKey)
except WindowsError:
print r'Message: No Ndi\Interfaces Key'
循环结束,目前只提供修改一个网卡IP的功能
_winreg.CloseKey(hSubKey)
_winreg.CloseKey(hkey)
通过修改注册表设置IP
strKeyName = 'System\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\' + netCfgInstanceID
print '网络适配器的注册表地址是:\n', strKeyName
hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \
strKeyName, \
0, \
_winreg.KEY_WRITE)
config = ConfigParser.ConfigParser()
print
print '正在打开IP.ini配置文件…'
config.readfp(open('IP.ini'))
IPAddress = config.get("school","IPAddress")
SubnetMask = config.get("school","SubnetMask")
GateWay = config.get("school","GateWay")
DNSServer1 = config.get("school","DNSServer1")
DNSServer2 = config.get("school","DNSServer2")
DNSServer = [DNSServer1,DNSServer2]
print '配置文件内设定的信息如下,请核对:'
print
print 'IP地址:', IPAddress
print '子关掩码:', SubnetMask
print '默认网关:', GateWay
print '主DNS服务器:', DNSServer1
print '次DNS服务器:', DNSServer2
print
res = raw_input('现在,请您决定:输入1,则将配置文件写入系统;输入2,则将现有的系统设定还原为全部自动获取;否则程序退出:')
if str(res) == '1':
try:
_winreg.SetValueEx(hkey, 'EnableDHCP', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'IPAddress', None, _winreg.REG_MULTI_SZ, [IPAddress])
_winreg.SetValueEx(hkey, 'SubnetMask', None, _winreg.REG_MULTI_SZ, [SubnetMask])
_winreg.SetValueEx(hkey, 'DefaultGateway', None, _winreg.REG_MULTI_SZ, [GateWay])
_winreg.SetValueEx(hkey, 'NameServer', None, _winreg.REG_SZ, ','.join(DNSServer))
except WindowsError:
print 'Set IP Error'
exit()
_winreg.CloseKey(hkey)
print '切换成功!重置网络后即可生效'
elif str(res) == '2':
try:
_winreg.SetValueEx(hkey, 'EnableDHCP', None, _winreg.REG_DWORD, 0x00000001)
_winreg.SetValueEx(hkey, 'T1', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'T2', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'NameServer', None, _winreg.REG_SZ, None)
_winreg.SetValueEx(hkey, 'DhcpConnForceBroadcastFlag', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'Lease', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'LeaseObtainedTime', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'LeaseTerminatesTime', None, _winreg.REG_DWORD, 0x00000000)
except WindowsError:
print 'Set IP Error'
exit()
_winreg.CloseKey(hkey)
print '切换成功!重置网络后即可生效'
else:
print '用户手动取消,程序退出'
exit('')
E. 用python调用outlook发邮件的问题
我把你的错误信息打印出来。''这个意思是“已终止操作”
现在看来是com出了错误。我没有调 过outlook。不过我觉着应该可以成功。因为COM接口的文档少。
你可以先从VBA文档 里学习一下这个接口。再找一些C++调用outlook的例子。
下面是我从网上找的一个例子。仅供参考
#!/usr/bin/envpython
"""
Asimpleaddressbookbrowser.Descendintothedepthsof
list.Thenextractthosecontacts!
NOTE:.
MailMessages
-------------
InMSDN,"Messagingand
Collaboration","CollaborationDataObjects","CDOfor
Windows2000","CDOforWindows2000","Messaging",
"Concepts","CDOMessagingCOMInterfaces","TheIMessage
COMInterface","IMessageProperties".
Unfortunately,.
Indeed,the'gen_py'directoryinside'site-packages'maybe
.
SavedItems
-----------
typedefenum{
olTXT=0,
olRTF=1,
olTemplate=2,
olMSG=3,
olDoc=4,
olHTML=5,
olVCard=6,
olVCal=7
}OlSaveAsType;
.
.
.
.
"""
importwin32com.client
importsys,os
#.
outlook=win32com.client.Dispatch("Outlook.Application")
classView:
"Aviewontonamespaces."
def__init__(self,encoding):
"'encoding'."
self.encoding=encoding
classConsoleView(View):
"Aconsole-styleview."
show_namespace_property_mapping={
win32com.client.constants.olFolder:
("+","Name"),
win32com.client.constants.olContact:
(">","Email1Address"),
win32com.client.constants.olMail:
(">","Subject"),
None:
("?","Name")
}
def__init__(self,encoding,page_width=80,page_limit=20):
"""
'encoding'andtheoptional
'page_width'and'page_limit'.
"""
View.__init__(self,encoding)
self.page_width=page_width
self.page_limit=page_limit
defupdate_status(self,counter,max_value):
"'counter'valueand'max_value'."
last_counter=max(counter-1,0)
last_width=int((last_counter*self.page_width)/max_value)
width=int((counter*self.page_width)/max_value)
sys.stdout.write("."*(width-last_width))
ifcounter==max_value:
sys.stdout.write(" ")
deferror(self):
sys.stdout.write("!")
defshow_namespace(self,items):
"Showthenamespace,givenalistof'items'."
iflen(items)>self.page_limit:
print"!","Showingthefirst",self.page_limit,"itemsonly."
forvalueinitems[:self.page_limit]:
try:
decoration,property=self.show_namespace_property_mapping[value.Class]
exceptKeyError:
decoration,property=self.show_namespace_property_mapping[None]
printdecoration,self.get_property(value,property).encode(self.encoding)
defget_property(self,object,property,default=""):
try:
#NOTE:Hack!
ifproperty=="SentOn":
returngetattr(object,property).Format()
returngetattr(object,property)
exceptAttributeError:
returndefault
classExtractor:
"/objectsfromfolders."
extract_type_mapping={
win32com.client.constants.olAppointment:
(win32com.client.constants.olVCal,"vcs"),
win32com.client.constants.olContact:
(win32com.client.constants.olVCard,"vcf"),
win32com.client.constants.olMail:
(win32com.client.constants.olTXT,"txt"),
None:
(win32com.client.constants.olTXT,"txt")
}
def__init__(self,view=None):
"'view'."
self.view=view
defextract(self,items,filename):
"Extractthegiven'items'toafilewiththegiven'filename'."
total_number=len(items)
foriinrange(0,total_number):
value=items[i]
try:
save_as_type,suffix=self.extract_type_mapping[value.Class]
exceptKeyError:
save_as_type,suffix=self.extract_type_mapping[None]
try:
value.SaveAs(os.path.join(filename,str(i)+"."+suffix),
save_as_type)
exceptAttributeError:
ifself.view:
self.view.error()
exceptwin32com.client.pywintypes.com_error:
ifself.view:
self.view.error()
ifself.view:
self.view.update_status(i+1,total_number)
classExplorer:
"."
def__init__(self,view=None):
globaloutlook
self.current=self.ns=outlook.GetNamespace("MAPI")
self.view=view
self._get_namespace()
defup(self):
"."
ifself.current!=self.ns:
self.current=self.current.Parent
self._get_namespace()
return1
return0
defdown(self,name):
"""
'name'returningwhetherit
couldbedone.
"""
ifself.choices.has_key(name):
self.current=self.choices[name]
self._get_namespace()
return1
return0
defget_items(self):
"."
returnself.items
defget_choices(self):
"."
returnself.choices
def_get_namespace(self):
"""
.
"""
self.choices,self.items=get_namespace(self.current,self.view)
defget_namespace(namespace,view=None):
"""
Getthecontentsofthegiven'namespace',returningadictionaryof
choices(appropriateforfolders)andalistofitems(appropriatefor
messages).
"""
d={}
l=[]
#Firsttrylookingforfolders.Thenlookforitems.Andsoon.
forpropertiesin(("Folders","Name"),("Items",None)):
#:folders,items,etc.
object_name=properties[0]
try:
subobject=getattr(namespace,object_name)
exceptAttributeError:
#
#thenextiteration.
continue
#.
#Cannotsliceitems,.
total_number=len(subobject)
foriinrange(1,total_number+1):
try:
field_name=properties[1]
#,if
#specified.
l.append(subobject[i])
iffield_nameisnotNone:
d[getattr(subobject[i],field_name)]=subobject[i]
exceptAttributeError:
pass
#Crudestatusindicator.
ifview:
view.update_status(i,total_number)
returnd,l
defmain():
#Gettheencodingifspecified.
iflen(sys.argv)>2:
encoding=sys.argv[2]
else:
encoding="UTF-8"
view=ConsoleView(encoding)
explorer=Explorer(view)
while1:
#Prompttheuser.
print"-"*60
view.show_namespace(explorer.get_items())
print"-"*60
print"[U]p[D]own[E]xtract[Q]uit[H]elpthen<Return>!"
print"-"*60
s=raw_input().strip().upper()[0]
#Findtherightaction.
ifs=="U":
#Up!
explorer.up()
elifs=="D":
#Promptforthefoldertoenter.
print"Downinto:"
name=raw_input()
ifnotexplorer.down(name):
print"Nosuchobject."
elifs=="E":
#Promptforthefiletoextractto.
print"Extractto:"
filename=raw_input()
print"Extracting..."
extractor=Extractor(view)
extractor.extract(explorer.get_items(),filename)
elifs=="Q":
print"Exiting..."
raiseSystemExit
elifs=="H":
print"TypetheDkeythen<Return>toenterafolder."
print"<Return>."
print"TypetheUkeythen<Return>tomoveuponelevel."
print"TypetheQkeythen<Return>toquit."
print"TypetheHkeythen<Return>toreadthisagain."
print"TypetheEkeythen<Return>toextractitems."
print"<Return>."
print"Goodluck!"
else:
print"Nosuchcommand."
if__name__=="__main__":
main()
#vim:tabstop=4expandtabshiftwidth=4
F. Python如何实现图片特征点匹配
python-opencv-特征点匹配连线(画线)drawMatches
Python 没有OpenCV 2.4.13版本的cv2.drawMatches(),无法直接使用,故可参看本文第2节的drawMatches函数使用
Python 有OpenCV 3.0.0版本的cv2.drawMatches(),可以直接使用
1、drawMatches数据结构(opencv2.4.13)
Draws the found matches of keypoints from two images.
C++:
Parameters:
img1– First source image.
keypoints1– Keypoints from the first source image.
img2– Second source image.
keypoints2– Keypoints from the second source image.
matches1to2– Matches from the first image to the second one, which means that keypoints1[i] has a corresponding point in keypoints2[matches[i]] .
outImg – Output image. Its content depends on the flags value defining what is drawn in the output image. See possible flags bit values below.
matchColor– Color of matches (lines and connected keypoints). If matchColor==Scalar::all(-1) , the color is generated randomly.
singlePointColor – Color of single keypoints (circles), which means that keypoints do not have the matches. If singlePointColor==Scalar::all(-1) , the color is generated randomly.
matchesMask– Mask determining which matches are drawn. If the mask is empty, all matches are drawn.
flags– Flags setting drawing features. Possible flags bit values are defined by DrawMatchesFlags.
This function draws matches of keypoints from two images in the output image. Match is a line connecting two keypoints (circles). The structure DrawMatchesFlags is defined as follows:
2、drawMatches(python实现)
G. python嵌套C语言、调用外部C的dll,python实参如何传递并修改
handle = ctypes.c_int(0)
ret = lib.XF_OpenDev(0, ctypes.byref(handle))
handle作为指吵配针传进去后如果升皮指被改掉,返回握薯的是一个c_int 或者c_long, 你可以通过handle.value来获得可以在python中灵活运用的真正的python整形
H. python获取串口设备的描述
importwinreg
key=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r"{36FC9E60-C465-11CF-8056-444553540000}")
foriinrange(winreg.QueryInfoKey(key)[0]):
subkey=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,"SYSTEM\ControlSet001\Control\Class\{36FC9E60-C465-11CF-8056-444553540000}\"+winreg.EnumKey(key,i))
print(winreg.QueryValueEx(subkey,'DriverDesc'))
winreg.CloseKey(subkey)
winreg.CloseKey(key)
importwinreg
key=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r"")
try:
i=0
while1:
name,value,type=winreg.EnumValue(key,i)
print(repr(name),value)
i+=1
value,type=winreg.QueryValueEx(key,"EnableAutoTray")
exceptFileNotFoundError:
exceptOSError:
以前回答过一个,好像跟你说的意思差不多,都是读取注册表,一个读USB,一个是串口