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,一個是串口