第2章 Python语言基础

  1. Python环境的搭建
  2. 编写第一个Python程序
  3. Python模块的安装和使用
  4. Python语言的序列、控制结构、文件处理、异常处理结构
  5. Socket网络编程的基础知识
  6. 可执行文件的转换

1.Python环境的搭建

参考资料:

  • Python官网: http://www.python.org/
  • Python 3官方文档:http://docs.python.org/3/
  • python 3中文教程:Python3 教程 | 菜鸟教程

安装及下载:略

2.编写第一个Python程序




python 列表成绩单排序 python按成绩排序_python 列表成绩单排序


3.Python模块的安装与使用


python 列表成绩单排序 python按成绩排序_python 字典排序成绩_02


python 列表成绩单排序 python按成绩排序_python 字典排序成绩_03


4.Python序列结构

在Python中,序列是最基本的数据结构,相当于C语言中的数组结构。Python中序列结构包括列表、元组、字典等。


# 1.列表

# 创建列表
student = ['number', 'name', 'age']
num = list((1, 2, 3, 4, 5, 6, 7, 8, 9))
print('name: {}nnum: {}'.format(student, num))

# 删除列表
list_test = ['m', 's', 0, 8, 0, 6, 7]
del list_test[1]
print('del list_test[1]: {}'.format(list_test))
del list_test
# print('del list_test:{}'.format(list_test))
# Traceback (most recent call last):
#   File "D:/array_python.py", line 20, in <module>
#     print('del list_test:{}'.format(list_test))
# NameError: name 'list_test' is not defined

# 在列表尾部添加元素
list_test = ['m', 's', 0, 8, 0, 6, 7]
list_test.append(8)
print('list_test.append(8): {}'.format(list_test))

list_test_2 = ['m', 's', 0, 8, 0, 6, 7]
list_test.extend(list_test_2)
print('list_test.extend(list_test_2): {}'.format(list_test))

# 在列表的指定位置添加元素
list_test = ['m', 's', 0, 8, 0, 6, 7]
demo = '.com'
list_test.insert(7, demo)
print('list_test.insert(7, demo): {}'.format(list_test))

# 删除列表中首次出现的元素
list_test = ['m', 's', 0, 8, 0, 6, 7]
list_test.remove(0)
print('list_test.remove(0): {}'.format(list_test))
# 删除并返回列表中指定下标的元素
list_test = ['m', 's', 0, 8, 0, 6, 7]
# 删除并返回列表list_test中下标元素,默认值为-1
print('list_test.pop(): {}  list_test: {}'.format(list_test.pop(), list_test))
# 删除并返回列表list_test中下标为0的元素
print('list_test.pop(0): {}  list_test: {}'.format(list_test.pop(0), list_test))

# 返回指定元素在列表list_test中出现的次数
list_test = ['m', 's', 0, 8, 0, 6, 7]
print("list_test.count(0): {}nlist_test.count('m'): {}".format(list_test.count(0), 
                                                                list_test.count('m')))

# 将列表中的所有元素逆序
list_test = ['m', 's', 0, 8, 0, 6, 7]
list_test.reverse()
print("after list_test.reverse(): {}".format(list_test))
# 对列表中的元素进行排序
list_test = ['m', 's', 0, 8, 0, 6, 7]
list_test.sort(key=str, reverse=False)
print("after list_test.sort(key=str, reverse=False): {}".format(list_test))


# 2.元组
# 元组与列表不同,属于不可变序列,一旦创建后便无法对元素进行增删改,但是对元素的访问速度要比列表快得多。
tuple_test = ('m', 's', 0, 8, 0, 6, 7)
print("tuple_test: {}".format(tuple_test))


# 3.字典
# 建立字典
dic_test = {'lab': 'ms08067',
            'url': 'http://ms08067.com'}
print("dic_test: {}".format(dic_test))
dic_test = dict(lab='ms08067', url='http://ms08067.com')
print("dic_test: {}".format(dic_test))
# 修改字典中的元素
dic_test = {'name': 'xiao ming', 'age': 26, 'sex': 'male'}
dic_test['age'] = 25
print("dic_test: {}".format(dic_test))
# 为字典添加新元素
dic_test = {'name': 'xiao ming', 'age': 26}
dic_test['sex'] = 'male'
print("dic_test: {}".format(dic_test))
# 返回字典中的所有元素
dic_test = {'name': 'xiao ming', 'age': 26, 'sex': 'male'}
print("dic_test.items(): {}".format(dic_test.items()))
# 删除字典中的元素
dic_test = {'name': 'xiao ming', 'age': 26, 'sex': 'male'}
del dic_test['sex']
print("dic_test: {}".format(dic_test))


5.Python控制结构


# 1.选择结构
student_score = int(input("Scores of students:"))
if student_score < 60:
    print("不及格")
elif 60 <= student_score <= 80:
    print("良好")
else:
    print("优秀")

# 2.循环结构
# for循环
sum_num = 0
for i in range(1, 101):
    sum_num = sum_num + i
else:
    print('sum_num: ', sum_num)
# while循环
x = int(input('x='))
sum_num = 0
while x != 0:
    sum_num = sum_num + x
    x = x - 1
else:
    print('sum_num = ', sum_num)


6.Python文件处理


# 1.打开文件并创建对象
string = 'hello world! n'
f = open('demo.txt', 'w')
f.write(string)
f.close()
# 向已经存在的demo.txt文件中写入"hello China!",且不清空原始内容
string = 'hello China!'
f = open('demo.txt', 'a')
f.write(string)
f.close()
# 读取文件内容
f = open('demo.txt', 'r')
print(f.readline())
f.close()
# 读取demo.txt文件的所有内容
f = open('demo.txt', 'r')
print(f.read())
f.close()
# 推荐的打开方式(自动关闭并处理现场)
with open('demo.txt', 'a') as f:
    f.write('nhello ms08067')


7.Python异常处理结构


# 1.try...except...结构
math_score = input('数学成绩:')
try:
    math_score = int(math_score)
    if 0 <= math_score <= 100:
        print("输入的数学成绩为:", math_score)
    else:
        print("输入不在成绩范围内。")
except Exception as e:
    print('输入数值有误!')

# 2.try...except...else...结构
math_score = input('数学成绩:')
try:
    math_score = int(math_score)
except Exception as e:
    print('输入数值有误!')
else:
    if 0 <= math_score <= 100:
        print("输入的数学成绩为:", math_score)
    else:
        print("输入不在成绩范围内。")

# 3.try...except...finally...结构
a = int(input('a: '))
b = int(input('b: '))
try:
    div = a/b
    print(div)
except Exception as e:
    print('The second parameter cannot be 0.')
finally:
    print('运行结束!')


8.Socket网络编程

TCP服务端代码:


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8002))
s.listen(1)
print('Listen  at port:8002')
conn, addr = s.accept()
print('Connected by ', addr)
while True:
    data = conn.recv(1024)
    data = data.decode()
    print('Recv:', data)
    c = input('Input the content you want to send:')
    conn.sendall(c.encode())
    if c.lower() == 'bye':   # 转小写
        break
conn.close()
s.close()


TCP客户端代码:


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect(('127.0.0.1', 8002))
except Exception as e:
    print('server not found or not open')
while True:
    c = input('Input the content you want to send:')
    s.sendall(c.encode())
    data = s.recv(1024).decode()
    print('Recv:', data)
    if c.lower() == 'bye':
        break
s.close()


UDP服务端代码:


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 8001))
while True:
    data, addr = s.recvfrom(1024)
    print(data.decode())
    if data.decode().lower() == 'exit':
        break

s.close()


UDP客户端代码:


import socket
import uuid
import sys

def get_mac_address():
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
    return ":".join([mac[e:e+2] for e in range(0,11,2)])


ip = socket.gethostbyname(socket.gethostname())
mac = get_mac_address()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

info = "ip addr:" + ip + "n" + "mac addr:" + mac

s.sendto(info.encode(), ("127.0.0.1", 8001))
s.sendto(sys.argv[1].encode(), ("127.0.0.1", 8001))
s.close()


一个文件传输服务器的例子:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File    : Fileserver.py

import socketserver
import os
import re
import json
import struct
from optparse import OptionParser

def sendFile(conn, head_info,head_info_len,filename):
    try:
        conn.send(head_info_len)
        conn.send(head_info.encode('utf-8'))
        with open(filename, 'rb') as f:
            conn.sendall(f.read())
        print('[+]send success! '+filename)
    except:
        print('[-]send fail! ' + filename)

def operafile(filename):
    filesize_bytes = os.path.getsize(filename)
    pattern = re.compile(r'([^<>/|:""*?]+.w+$)')
    data = pattern.findall(filename)
    head_dir = {
        'filename': data,
        'filesize_bytes': filesize_bytes,
    }
    head_info = json.dumps(head_dir)
    head_info_len = struct.pack('i', len(head_info))
    return head_info_len, head_info

class MyServer(socketserver.BaseRequestHandler):
    buffsize = 1024
    def handle(self):
        print('[+]远程客户端ip地址:', self.client_address[0],'n')
        while True:
            filename = input('请输入要发送的文件名>>>').strip() #移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
            if(filename == "exit"):
                break
            head_info_len, head_info = operafile(filename)
            sendFile(self.request,head_info,head_info_len,filename)
        self.request.close()

def main():
    parser = OptionParser("Usage:%prog -p <port> ")   # 输出帮助信息
    parser.add_option('-p',type='string',dest='port',help='specify targer port')   # 获取ip地址参数
    options,args = parser.parse_args()
    port = int(options.port)

    print("[+]listening at " + str(port))
    s = socketserver.ThreadingTCPServer(('0.0.0.0', port), MyServer)  #
    s.serve_forever()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("interrupted by user, killing all threads...")




#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File    : Fileclient.py

from socket import *
import os
import sys
import json
import struct
from optparse import OptionParser

def recv_file(head_dir, tcp_client):
    filename = head_dir['filename']
    filesize = head_dir['filesize_bytes']
    print("[+]filename: "+filename[0])
    print("[+]filesize: "+ str(filesize))
    recv_len = 0
    f = open(filename[0], 'wb')
    while recv_len < filesize:
        if(filesize > 1024):
            recv_mesg = tcp_client.recv(1024)
            recv_len += len(recv_mesg)
            f.write(recv_mesg)
        else:
            recv_mesg = tcp_client.recv(filesize)
            recv_len += len(recv_mesg)
            f.write(recv_mesg)
    f.close()
    print('[+]文件传输完成!')

def main():
    parser = OptionParser("Usage:%prog -u <target address> -p <port> ")   # 输出帮助信息
    parser.add_option('-u', type='string', dest='ip', help='specify targer ip')  # 获取ip地址参数
    parser.add_option('-p', type='string', dest='port', help='specify targer port')   # 获取ip地址参数
    options,args = parser.parse_args()
    target_port = int(options.port)
    target_ip = options.ip

    tcp_client = socket(AF_INET, SOCK_STREAM)  # socket初始化
    ip_port = ((target_ip, target_port))
    tcp_client.connect_ex(ip_port)
    print('[+]等待服务端应答数据....')
    struct_len = tcp_client.recv(4)  # 接收报头长度
    struct_info_len = struct.unpack('i', struct_len)[0]  # 解析得到报头信息的长度
    print("[+]接收头信息长度:" + str(struct_info_len))
    head_info = tcp_client.recv(struct_info_len)
    head_dir = json.loads(head_info.decode('utf-8'))  # 将报头的内容反序列化
    print("[+]输出头部信息内容:" + str(head_dir))
    recv_file(head_dir, tcp_client)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("interrupted by user, killing all threads...")


9.可执行文件的转换


import os

def banner():
    print('########################################################################################n'
          '###################################-->贝塔安全实验室<--##################################n'
          '########################################################################################n')

def start():
    banner()
    info = os.system("whoamin")
    while True:
        info = input("n Btea->")
        os.system(info)

if __name__ == '__main__':
    try:
        start()
    except KeyboardInterrupt:
        print("interrupted by user, killing all threads...")


在win7下的打包效果:


(py36Env) D:>pyinstaller -F -i cmd.ico cmd.py
206 INFO: PyInstaller: 4.1
207 INFO: Python: 3.6.8
207 INFO: Platform: Windows-7-6.1.7601-SP1
209 INFO: wrote D:2.9.1cmd.spec
223 INFO: UPX is not available.
226 INFO: Extending PYTHONPATH with paths
['D:2.9.1',
 'D:2.9.1']
316 INFO: checking Analysis
321 INFO: Building because inputs changed
322 INFO: Initializing module dependency graph...
328 INFO: Caching module graph hooks...
374 INFO: Analyzing base_library.zip ...
22025 INFO: Caching module dependency graph...
22185 INFO: running Analysis Analysis-00.toc
22229 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of
final executable
  required by c:usersadministrator.user-20200521wfenvspy36envscriptspython
.exe
22736 INFO: Analyzing D:2.9.1cmd.py
22741 INFO: Processing module hooks...
22742 INFO: Loading module hook 'hook-difflib.py' from 'c:usersadministrator
.user-20200521wfenvspy36envlibsite-packagesPyInstallerhooks'...
22745 INFO: Excluding import of doctest from module difflib
22746 INFO: Loading module hook 'hook-encodings.py' from 'c:usersadministrat
or.user-20200521wfenvspy36envlibsite-packagesPyInstallerhooks'...
22920 INFO: Loading module hook 'hook-heapq.py' from 'c:usersadministrator.u
ser-20200521wfenvspy36envlibsite-packagesPyInstallerhooks'...
22923 INFO: Excluding import of doctest from module heapq
22924 INFO: Loading module hook 'hook-pickle.py' from 'c:usersadministrator.
user-20200521wfenvspy36envlibsite-packagesPyInstallerhooks'...
22926 INFO: Excluding import of argparse from module pickle
22927 INFO: Loading module hook 'hook-xml.py' from 'c:usersadministrator.use
r-20200521wfenvspy36envlibsite-packagesPyInstallerhooks'...
23635 INFO: Looking for ctypes DLLs
23635 INFO: Analyzing run-time hooks ...
23646 INFO: Looking for dynamic libraries
23811 INFO: Looking for eggs
23811 INFO: Using Python library c:usersadministrator.user-20200521wfenvspy3
6envscriptspython36.dll
23812 INFO: Found binding redirects:
[]
23818 INFO: Warnings written to D:2.9.1buildcmdwarn-cmd.txt
23894 INFO: Graph cross-reference written to D:2.9.1buildcmdxref-cmd.html
23915 INFO: checking PYZ
23918 INFO: Building because name changed
23918 INFO: Building PYZ (ZlibArchive) D:2.9.1buildcmdPYZ-00.pyz
25042 INFO: Building PYZ (ZlibArchive) D:2.9.1buildcmdPYZ-00.pyz completed succes
sfully.
25062 INFO: checking PKG
25066 INFO: Building because name changed
25066 INFO: Building PKG (CArchive) PKG-00.pkg
30186 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
30232 INFO: Bootloader c:usersadministrator.user-20200521wfenvspy36envlibs
ite-packagesPyInstallerbootloaderWindows-64bitrun.exe
30233 INFO: checking EXE
30240 INFO: Building because name changed
30241 INFO: Building EXE from EXE-00.toc
30258 INFO: Copying icons from ['cmd.ico']
30265 INFO: Writing RT_GROUP_ICON 0 resource with 20 bytes
30266 INFO: Writing RT_ICON 1 resource with 67624 bytes
30286 INFO: Updating manifest in D:2.9.1buildcmdrun.exe.6cjz5g5s
30294 INFO: Updating resource type 24 name 1 language 0
30308 INFO: Appending archive to EXE D:2.9.1distcmd.exe
30359 INFO: Building EXE from EXE-00.toc completed successfully.

(py36Env) D:2.9.1>


python 列表成绩单排序 python按成绩排序_Python_04


10.小结

  • Python语言简介
  • Windows下打包方式