标签: python

  • python显示数字时关闭科学计数法

    默认情况下如果数值非常大或非常小会显示为科学计数法,用f-string可以指定数字的显示格式。
    参考这里的说明:https://docs.python.org/zh-cn/3/library/string.html#formatspec

    f或F类型会用定点数输出数值,不会用科学计数法显示数字。用法如下:

    f'{num:f}’ 根据内容自动确定显示位数
    f'{num:5f}’ 最小总宽度显示为5位,不足部分在左边用空格填充,最大宽度则由内容决定
    f'{num:05f}’ 最小总宽度显示为5位,不足部分在左边用0填充,最大宽度则由内容决定
    f'{num:.2f}’ 小数点后最少显示5位,不足部分在右边用0填充,超出部分四舍五入
    f'{num:5.2f}’ 总宽度最少显示5位,不足部分在左边用空格填充,最大宽度则由内容决定,小数点后最少显示2位,不足部分在右边用0填充,超出部分四舍五入
    f'{num:05.2f}’ 总宽度最少显示5位,不足部分在左边用0填充,最大宽度则由内容决定,小数点后最少显示2位,不足部分在右边用0填充,超出部分四舍五入

    from decimal import Decimal
    
    num = Decimal("8.355")
    print(f'{num:f}')
    print(f'{num:5f}')
    print(f'{num:05f}')
    print(f'{num:.5f}')
    print(f'{num:5.2f}')
    print(f'{num:05.2f}')
    

    输出的结果为:

    8.355
    8.355
    8.355
    8.35500
     8.36
    08.36
    

    注意:
    python的四舍五入采用的是四舍六入五成双,具体可以看这篇文章:
    https://www.cnblogs.com/gxfaxe/p/14970856.html
    f-string的更多用法可以参考这里:
    https://zhuanlan.zhihu.com/p/668918715

    Views: 104

  • python或pyinstaller报”source code string cannot contain null bytes”

    pyinstaller报这个错误是因为python版本太低,不支持某些语法
    python报这个错误可能因为py文件损坏,加密,换行符,字符编码等问题

    Views: 243

  • python捕获ctrl+c中断的两种方法

    1,try…except…

        try:
            while True:
                time.sleep(100)
        except KeyboardInterrupt:
            print('Got signal: SIGINT, shutting down.')
            exit(0)
    

    2, 信号处理

    def handler(signal_received, frame):
        # Handle any cleanup here
        if signal_received == signal.SIGINT:
            print('SIGINT or CTRL-C detected. Exiting gracefully')
            exit(0)
    if __name__ == '__main__':
        signal.signal(signal.SIGINT, handler=handler) # ctlr + c
    

    建议用try…except的方法,通用性强,代码易读性高。

    Views: 61

  • python实现非塞UDP通信的两种方法

    当使用阻塞式UDP socket时无法执行多任务处理,也无法与用户交互,甚至不能响应ctrl+c中断。为了解决这些问题所以要用非阻塞式udp通信。
    1,多线程法

    import socket
    import signal
    import threading
    import time
    
    def handler(signal_received, frame):
        # Handle any cleanup here
        if signal_received == signal.SIGINT:
            print('SIGINT or CTRL-C detected. Exiting gracefully')
            exit(0)
    
    def task(host, port):
        print("udp server is listen on " + str(host) + ':' + str(port))
    
        sock = socket.socket(socket.AF_INET, # Internet
                            socket.SOCK_DGRAM) # UDP
        sock.bind((UDP_IP, UDP_PORT))
    
        while True:
            data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
            print("from %s received message: %s" % (addr, data))
    
    if __name__ == '__main__':
        signal.signal(signal.SIGINT, handler=handler) # ctlr + c
    
        UDP_IP = "0.0.0.0"
        UDP_PORT = 5005
    
        t = threading.Thread(target=task, args=(UDP_IP, UDP_PORT))
        t.daemon = True
        t.start()
    
        while True:
            time.sleep(100)
    

    2, 协程法
    官方文档说不要在应用中使用asyncio,而是应该在框架中用

    import asyncio
    
    class EchoServerProtocol:
        def __init__(self, message, on_con_lost):
            self.message = message
            self.on_con_lost = on_con_lost
            self.transport = None
    
        def connection_made(self, transport):
            self.transport = transport
    
        def datagram_received(self, data, addr):
            print('Received %r from %s' % (data.decode(), addr))
            self.transport.sendto(data, addr)
        def error_received(self, exc):
            print('Error received:', exc)
        def connection_lost(self, exc):
            print("Connection closed")
            self.on_con_lost.set_result(True)
    
    async def main():
        print("Starting UDP server")
    
        # Get a reference to the event loop as we plan to use
        # low-level APIs.
        loop = asyncio.get_running_loop()
        on_con_lost = loop.create_future()
        message = 'Hello World!'
        # One protocol instance will be created to serve all
        # client requests.
        transport, protocol = await loop.create_datagram_endpoint(
            lambda: EchoServerProtocol(message, on_con_lost=on_con_lost),
            local_addr=('127.0.0.1', 9999),
            remote_addr=('127.0.0.1', 5005))
    
        try:
            while True:
                await asyncio.sleep(10)  # Serve for 1 hour.
        finally:
            transport.close()
    
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print('Got signal: SIGINT, shutting down.')
        exit(0)
    

    Views: 89