python常用模塊


1Time

import time

print(time.time())
print(time.clock())#計算cpu執行時間
print(time.gmtime())#世界標准時間
print(time.strftime())  #Commonly used format codes:  設置時間第一個參數為設置時間格式
                            # %Y  Year with century as a decimal number.
                            # %m  Month as a decimal number [01,12].
                            # %d  Day of the month as a decimal number [01,31].
                            # %H  Hour (24-hour clock) as a decimal number [00,23].
                            # %M  Minute as a decimal number [00,59].
                            # %S  Second as a decimal number [00,61].
                            # %z  Time zone offset from UTC.
                            # %a  Locale's abbreviated weekday name.
                            # %A  Locale's full weekday name.
                            # %b  Locale's abbreviated month name.
                            # %B  Locale's full month name.
                            # %c  Locale's appropriate date and time representation.
                            # %I  Hour (12-hour clock) as a decimal number [01,12].
                            # %p  Locale's equivalent of either AM or PM.
print(time.strptime())#字符串時間轉換為結構化時間 第一個參數為字符串第二個為時間格式
print(time.ctime())#當前時間格式固定 參數轉化為標准時間從1970年開始算
print(time.mktime())#轉換為時間戳
import datetime
print(datetime.datetime.now())#直接看時間

2logging模塊

日志格式:

 

 

 

import logging

# logging.debug('debug message')
# logging.info('info message')
# logging.warning('warning message')
# logging.error('error message')
# logging.critical('critical message')
#
# logging.basicConfig(level=logging.DEBUG,#級別
#                     format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)',#格式
#                     datefmt='%a,%d %b %Y %H:%M:%S',#時間格式
#                     filename='/tmp/test.log',#文件目錄名字
#                     filemode='w')#設置輸出到文件

logger=logging.getLogger()
#創建一個handler,用於寫入日志文件
fh=logging.FileHandler('test.log')
#再創建一個handler,用於輸出控制台
ch=logging.StreamHandler()
logger.setLevel(logging.DEBUG)

formatter=logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)
View Code

3OS模塊

import os
os.getcwd()#獲得工作目錄
os.chdir()#更改當前腳本工作目錄
os.curdir#當前路徑
os.makedirs()#生成多層文件夾
os.removedirs()#刪除多層文件夾有內容的文件夾不刪除
os.mkdir()#生成文件夾只能創建一個文件夾
os.rmdir()#刪除一個文件夾
os.listdir()#輸出當前路徑下的文件文件夾
os.remove()#刪除一個文件
os.rename()#更改文件名
os.stat()#文件信息
os.sep()#輸出操作系統指定的路徑分隔符
os.linesep()#輸出終止符(換行符
os.pathsep()#路徑分隔符
os.system()#運行shell命令
os.environ#環境變量
os.path.abspath()#絕對路徑
os.path.split()#對路徑進行分割 路徑 文件名
os.path.dirname()#上一個文件夾的名字
os.path.basename()#返回最后文件名

os.path.join()#路徑拼接

4sys模塊

import sys #與python解釋器交互
# sys.argv()           #命令行參數List,第一個元素是程序本身路徑
# sys.exit()        #退出程序,正常退出時exit(0)
print(sys.version)      #獲取Python解釋程序的版本信息
# sys.maxint()        #最大的Int值
# sys.path()           #返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
# sys.platform()       #返回操作系統平台名稱
#sys.path.append()#添加路徑
sys.stdout.write('please:')#標准輸出

5hashlib模塊

import  hashlib#加密模塊
import time
m=hashlib.md5()
print(m)
t_start=time.time()
m.update('hello world'.encode('utf-8'))
time.sleep(2)
t_end=time.time()
print(t_end-t_start)
print(m.hexdigest())
s=hashlib.sha256()
s.update('hello world'.encode('utf-8'))
print(s.hexdigest())

6ConfigParser模塊

import  configparser
config=configparser.ConfigParser()
# config['DEFAULT']={'ServerAliveInterval':'45',
#                    'Compression':'yes',
#                    'CompressionLevel':'9'}
#
# config['bitbucket.org']={}
# config['bitbucket.org']['User']='hg'
# config['topsecret.server.com']={}
# topsecret=config['topsecret.server.com']
# topsecret['Host Port']='50022'
# topsecret['ForwardX11']='no'
# config['DEFAULT']['ForwardX11']='yes'
# with open('example.ini','w')as configfile:
#     config.write(configfile)
config.read('example.ini')
# print(config.sections())
# print(config.defaults())

# for key in config['bitbucket.org']:
#     print(key)
# config.remove_section('topsecret.server.com')


config.set('bitbucket.org','user','alex')
config.write(open('example.ini','w'))

7json&pickle模塊

json,用於字符串 和 python數據類型間進行轉換

Json模塊提供了四個功能:dumps、dump、loads、load

import json
dic={'name':'alex','age':'18'}
data=json.dumps(dic)#轉換為json形式的仿字典
f=open('test','w')
f.write(data)
f.close()  #向文件寫入1


dic={'name':'alex','age':'18'}
f=open('test','w')
import json
json.dump(dic,f)
f.close()#向文件寫入2
import json

f=open('test','r')
# data=f.read()
# data=json.loads(data)#將json模式的仿字典轉化為python形式的字典
data=json.load(f)
f.close()
print(data['name'])  #從文件讀取數據

pickle,用於python特有的類型 和 python的數據類型間進行轉換

pickle模塊提供了四個功能:dumps、dump、loads、load

8shelve模塊

import shelve
f=shelve.open('shelve_module')

# f['info']={'name':'alex','age':'18'}
data=f.get('info')
print(data)

代碼運行后結果為

9xml處理模塊

xml是實現不同語言或程序之間進行數據交換的協議,跟json差不多,但json使用起來更簡單,不過,古時候,在json還沒誕生的黑暗年代,大家只能選擇用xml呀,至今很多傳統公司如金融行業的很多系統的接口還主要是xml。

xml的格式如下,就是通過<>節點來區別數據結構的:

 1 <?xml version="1.0"?>
 2 <data>
 3     <country name="Liechtenstein">
 4         <rank updated="yes">2</rank>
 5         <year>2008</year>
 6         <gdppc>141100</gdppc>
 7         <neighbor name="Austria" direction="E"/>
 8         <neighbor name="Switzerland" direction="W"/>
 9     </country>
10     <country name="Singapore">
11         <rank updated="yes">5</rank>
12         <year>2011</year>
13         <gdppc>59900</gdppc>
14         <neighbor name="Malaysia" direction="N"/>
15     </country>
16     <country name="Panama">
17         <rank updated="yes">69</rank>
18         <year>2011</year>
19         <gdppc>13600</gdppc>
20         <neighbor name="Costa Rica" direction="W"/>
21         <neighbor name="Colombia" direction="E"/>
22     </country>
23 </data>
View Code

xml協議在各個語言里的都 是支持的,在python中可以用以下模塊操作xml 

import xml.etree.ElementTree as ET
 
tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)
 
#遍歷xml文檔
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.tag,i.text)
 
#只遍歷year 節點
for node in root.iter('year'):
    print(node.tag,node.text)

修改和刪除xml文檔內容

import xml.etree.ElementTree as ET
 
tree = ET.parse("xmltest.xml")
root = tree.getroot()
 
#修改
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("updated","yes")
 
tree.write("xmltest.xml")
 
 
#刪除node
for country in root.findall('country'):
   rank = int(country.find('rank').text)
   if rank > 50:
     root.remove(country)
 
tree.write('output.xml')

自己創建xml文檔

import xml.etree.ElementTree as ET
 
 
new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text = '33'
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '19'
 
et = ET.ElementTree(new_xml) #生成文檔對象
et.write("test.xml", encoding="utf-8",xml_declaration=True)
 
ET.dump(new_xml) #打印生成的格式

10PyYAML模塊

Python也可以很容易的處理ymal文檔格式,只不過需要安裝一個模塊,參考文檔:http://pyyaml.org/wiki/PyYAMLDocumentation 

Subprocess模塊 

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

os.system os.spawn*

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.

The run() function was added in Python 3.5; if you need to retain compatibility with older versions, see the Older high-level API section.

subprocess.run(args*stdin=Noneinput=Nonestdout=Nonestderr=Noneshell=Falsetimeout=Nonecheck=False)

Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.

The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the Popen constructor - apart from timeoutinput and check, all the arguments to this function are passed through to that interface.

This does not capture stdout or stderr by default. To do so, pass PIPE for the stdout and/or stderr arguments.

The timeout argument is passed to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated.

The input argument is passed to Popen.communicate() and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if universal_newlines=True. When used, the internal Popen object is automatically created withstdin=PIPE, and the stdin argument may not be used as well.

If check is True, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.

常用subprocess方法示例

#執行命令,返回命令執行狀態 , 0 or 非0
>>> retcode = subprocess.call(["ls", "-l"])

#執行命令,如果命令結果為0,就正常返回,否則拋異常
>>> subprocess.check_call(["ls", "-l"])
0

#接收字符串格式命令,返回元組形式,第1個元素是執行狀態,第2個是命令結果 
>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')

#接收字符串格式命令,並返回結果
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'

#執行命令,並返回結果,注意是返回結果,不是打印,下例結果返回給res
>>> res=subprocess.check_output(['ls','-l'])
>>> res
b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n'

#上面那些方法,底層都是封裝的subprocess.Popen
poll()
Check if child process has terminated. Returns returncode

wait()
Wait for child process to terminate. Returns returncode attribute.


terminate() 殺掉所啟動進程
communicate() 等待任務結束

stdin 標准輸入

stdout 標准輸出

stderr 標准錯誤

pid
The process ID of the child process.

#例子
>>> p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
>>> p.stdout.read()
b'/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14% /\n'

 

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)
 
>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
 
>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

調用subprocess.run(...)是推薦的常用方法,在大多數情況下能滿足需求,但如果你可能需要進行一些復雜的與系統的交互的話,你還可以用subprocess.Popen(),語法如下:

p = subprocess.Popen("find / -size +1000000 -exec ls -shl {} \;",shell=True,stdout=subprocess.PIPE)
print(p.stdout.read())

可用參數:

    • args:shell命令,可以是字符串或者序列類型(如:list,元組)
    • bufsize:指定緩沖。0 無緩沖,1 行緩沖,其他 緩沖區大小,負值 系統緩沖
    • stdin, stdout, stderr:分別表示程序的標准輸入、輸出、錯誤句柄
    • preexec_fn:只在Unix平台下有效,用於指定一個可執行對象(callable object),它將在子進程運行之前被調用
    • close_sfs:在windows平台下,如果close_fds被設置為True,則新創建的子進程將不會繼承父進程的輸入、輸出、錯誤管道。
      所以不能將close_fds設置為True同時重定向子進程的標准輸入、輸出與錯誤(stdin, stdout, stderr)。
    • shell:同上
    • cwd:用於設置子進程的當前目錄
    • env:用於指定子進程的環境變量。如果env = None,子進程的環境變量將從父進程中繼承。
    • universal_newlines:不同系統的換行符不同,True -> 同意使用 \n
    • startupinfo與createionflags只在windows下有效
      將被傳遞給底層的CreateProcess()函數,用於設置子進程的一些屬性,如:主窗口的外觀,進程的優先級等等

終端輸入的命令分為兩種:

    • 輸入即可得到輸出,如:ifconfig
    • 輸入進行某環境,依賴再輸入,如:python

需要交互的命令示例

import subprocess
 
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n ')
obj.stdin.write('print 2 \n ')
obj.stdin.write('print 3 \n ')
obj.stdin.write('print 4 \n ')
 
out_error_list = obj.communicate(timeout=10)
print out_error_list

subprocess實現sudo 自動輸入密碼

import subprocess
 
def mypass():
    mypass = '123' #or get the password from anywhere
    return mypass
 
echo = subprocess.Popen(['echo',mypass()],
                        stdout=subprocess.PIPE,
                        )
 
sudo = subprocess.Popen(['sudo','-S','iptables','-L'],
                        stdin=echo.stdout,
                        stdout=subprocess.PIPE,
                        )
 
end_of_pipe = sudo.stdout
 
print "Password ok \n Iptables Chains %s" % end_of_pipe.read()

 random

import random

print(random.random())#隨機數0到1
print(random.randint(1,8))#1 到8 的整數
print(random.choice())#在隨機序列里選擇
print(random.sample())#從序列里隨機選可以指定選幾個
print(random.randrange(1,8))#1到7 的整數 不包括右邊

 subproces

當我們需要調用系統的命令的時候,最先考慮的os模塊。用os.system()和os.popen()來進行操作。但是這兩個命令過於簡單,不能完成一些復雜的操作,如給運行的命令提供輸入或者讀取命令的輸出,判斷該命令的運行狀態,管理多個命令的並行等等。這時subprocess中的Popen命令就能有效的完成我們需要的操作。subprocess模塊允許一個進程創建一個新的子進程,通過管道連接到子進程的stdin/stdout/stderr,獲取子進程的返回值等操作。

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
This module intends to replace several other, older modules and functions, such as: os.system、os.spawn*、os.popen*、popen2.*、commands.*

這個模塊一個類:Popen。

 

 1 #Popen它的構造函數如下:
 2 subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None,stderr=None, preexec_fn=None, close_fds=False, shell=False,cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
 3 # 參數args可以是字符串或者序列類型(如:list,元組),用於指定進程的可執行文件及其參數。
 4 # 如果是序列類型,第一個元素通常是可執行文件的路徑。我們也可以顯式的使用executeable參
 5 # 數來指定可執行文件的路徑。在windows操作系統上,Popen通過調用CreateProcess()來創
 6 # 建子進程,CreateProcess接收一個字符串參數,如果args是序列類型,系統將會通過
 7 # list2cmdline()函數將序列類型轉換為字符串。
 8 # 參數bufsize:指定緩沖。我到現在還不清楚這個參數的具體含義,望各個大牛指點。
 9 # 參數executable用於指定可執行程序。一般情況下我們通過args參數來設置所要運行的程序。如
10 # 果將參數shell設為True,executable將指定程序使用的shell。在windows平台下,默認的
11 # shell由COMSPEC環境變量來指定。
12 # 參數stdin, stdout, stderr分別表示程序的標准輸入、輸出、錯誤句柄。他們可以是PIPE,
13 # 文件描述符或文件對象,也可以設置為None,表示從父進程繼承。
14 #
15 # 參數preexec_fn只在Unix平台下有效,用於指定一個可執行對象#(callable object),它將在子進程運行之前被調用。
16 # 參數Close_sfs:在windows平台下,如果close_fds被設置為True,則新創建的子進程將不會
17 # 繼承父進程的輸入、輸出、錯誤管道。我們不能將close_fds設置為True同時重定向子進程的標准輸入、輸出與錯誤(stdin, stdout, stderr)。
18 # 如果參數shell設為true,程序將通過shell來執行。
19 # 參數cwd用於設置子進程的當前目錄。
20 # 參數env是字典類型,用於指定子進程的環境變量。如果env = None,子進程的環境變量將從父進程中繼承。
21 # 參數Universal_newlines:不同操作系統下,文本的換行符是不一樣的。如:windows下
22 # 用’/r/n’表示換,而Linux下用’/n’。如果將此參數設置為True,Python統一把這些換行符當
23 # 作’/n’來處理。
24 # 參數startupinfo與createionflags只在windows下用效,它們將被傳遞給底層的
25 # CreateProcess()函數,用於設置子進程的一些屬性,如:主窗口的外觀,進程的優先級等等。
import subprocess

a = subprocess.Popen('ls')  # 創建一個新的進程,與主進程不同步

print('>>>>>>>', a)  # a是Popen的一個實例對象

'''
>>>>>>> <subprocess.Popen object at 0x10185f860>
__init__.py
__pycache__
log.py
main.py

'''
View Code
# subprocess.Popen('ls -l',shell=True)

# subprocess.Popen(['ls','-l'])

# subprocess.PIPE
#
# 在創建Popen對象時,subprocess.PIPE可以初始化stdin, stdout或stderr參數。表示與子進程通信的標准流。
# import subprocess
#
# # subprocess.Popen('ls')
# p = subprocess.Popen('ls', stdout=subprocess.PIPE)  # 結果跑哪去啦?
#
# print(p.stdout.read())  # 這這呢:b'__pycache__\nhello.py\nok.py\nweb\n'


# 這是因為subprocess創建了子進程,結果本在子進程中,if 想要執行結果轉到主進程中,就得需要一個管道,即 : stdout=subprocess.PIPE
#
# subprocess.STDOUT
#
# 創建Popen對象時,用於初始化stderr參數,表示將錯誤通過標准輸出流輸出。
#
# Popen的方法
# Popen.poll()
# 用於檢查子進程是否已經結束。設置並返回returncode屬性。
#
# Popen.wait()
# 等待子進程結束。設置並返回returncode屬性。
#
# Popen.communicate(input=None)
# 與子進程進行交互。向stdin發送數據,或從stdout和stderr中讀取數據。可選參數input指定發送到子進程的參數。 Communicate()返回一個元組:(stdoutdata, stderrdata)。注意:如果希望通過進程的stdin向其發送數據,在創建Popen對象的時候,參數stdin必須被設置為PIPE。同樣,如 果希望從stdout和stderr獲取數據,必須將stdout和stderr設置為PIPE。
#
# Popen.send_signal(signal)
# 向子進程發送信號。
#
# Popen.terminate()
# 停止(stop)子進程。在windows平台下,該方法將調用Windows API TerminateProcess()來結束子進程。
#
# Popen.kill()
# 殺死子進程。
#
# Popen.stdin
# 如果在創建Popen對象是,參數stdin被設置為PIPE,Popen.stdin將返回一個文件對象用於策子進程發送指令。否則返回None。
#
# Popen.stdout
# 如果在創建Popen對象是,參數stdout被設置為PIPE,Popen.stdout將返回一個文件對象用於策子進程發送指令。否則返回 None。
#
# Popen.stderr
# 如果在創建Popen對象是,參數stdout被設置為PIPE,Popen.stdout將返回一個文件對象用於策子進程發送指令。否則返回 None。
#
# Popen.pid
# 獲取子進程的進程ID。
#
# Popen.returncode
# 獲取進程的返回值。如果進程還沒有結束,返回None。


# supprocess模塊的工具函數
# supprocess模塊提供了一些函數,方便我們用於創建進程來實現一些簡單的功能。
#
# subprocess.call(*popenargs, **kwargs)
# 運行命令。該函數將一直等待到子進程運行結束,並返回進程的returncode。如果子進程不需要進行交
# 互, 就可以使用該函數來創建。
#
# subprocess.check_call(*popenargs, **kwargs)
# 與subprocess.call(*popenargs, **kwargs)
# 功能一樣,只是如果子進程返回的returncode不為0的話,將觸發CalledProcessError異常。在異常對象中,包
# 括進程的returncode信息。
#
# check_output(*popenargs, **kwargs)
# 與call()
# 方法類似,以byte
# string的方式返回子進程的輸出,如果子進程的返回值不是0,它拋出CalledProcessError異常,這個異常中的returncode包含返回碼,output屬性包含已有的輸出。
#
# getstatusoutput(cmd) / getoutput(cmd)
# 這兩個函數僅僅在Unix下可用,它們在shell中執行指定的命令cmd,前者返回(status, output),后者返回output。其中,這里的output包括子進程的stdout和stderr。


# import subprocess
#
# #1
# # subprocess.call('ls',shell=True)
# '''
# hello.py
# ok.py
# web
# '''
# # data=subprocess.call('ls',shell=True)
# # print(data)
# '''
# hello.py
# ok.py
# web
# 0
# '''
#
# #2
# # subprocess.check_call('ls',shell=True)
#
# '''
# hello.py
# ok.py
# web
# '''
# # data=subprocess.check_call('ls',shell=True)
# # print(data)
# '''
# hello.py
# ok.py
# web
# 0
# '''
# # 兩個函數區別:只是如果子進程返回的returncode不為0的話,將觸發CalledProcessError異常
#
#
#
# #3
# # subprocess.check_output('ls')#無結果
#
# # data=subprocess.check_output('ls')
# # print(data)  #b'hello.py\nok.py\nweb\n'

# 交互命令:
#
# 終端輸入的命令分為兩種:
#
# 輸入即可得到輸出,如:ifconfig
# 輸入進行某環境,依賴再輸入,如:python
# 需要交互的命令示例
View Code

一個例子(在socket編程中,傳輸命令返回結果,類似於xshell的交互):

 1 import subprocess
 2 
 3 
 4 import socket
 5 
 6 sk = socket.socket()  # 創建對象
 7 address = ('127.0.0.1', 8000)  # 端口號用1024之后的
 8 sk.bind(address)  # 綁定
 9 sk.listen(3)  # 最大可以有三個人等待
10 print('waiting.......')
11 while 1:
12     conn,addr=sk.accept()
13     print(addr)
14     while 1:
15         try:
16             data=conn.recv(1024)
17         except Exception:
18             break
19         if not data:break
20         print('.......',str(data,'utf8'))
21 
22         obj=subprocess.Popen(str(data,'utf8'),shell=True,stdout=subprocess.PIPE)#第一個是命令,第二個是shell=True第三個是管道命令
23         cmd_result=obj.stdout.read()
24         result_len=bytes(str(len(cmd_result)),'utf8')
25         conn.sendall(result_len)
26         conn.recv(1024)
27         conn.sendall(cmd_result)
cmd_server
 1 import socket
 2 
 3 sk=socket.socket()#創建客戶端 family type
 4 address=('127.0.0.1',8000)#22
 5 
 6 
 7 sk.connect(address)
 8 while True:
 9     inp=input('<<<')
10     if inp=='exit':
11         break
12     sk.send(bytes(inp,'utf8'))
13     result_len=int(str(sk.recv(1024),'utf8'))
14     sk.send(bytes('ok','utf8'))
15     data=bytes()
16     while len(data)!=result_len:
17         recv=sk.recv(1024)
18         data+=recv
19     print(str(data,'gbk'))
20 sk.close()
cmd_client

結果:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM