• 技术文章 >常见问题 >Python常见问题

    python如何操作剪切板?

    yangyang2020-05-21 10:50:29原创6593

    python中可以使用ctypes库来操作剪切板:

    1、调用get_clipboard() 获取剪切板数据

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    if __name__ == '__main__':

        # 获取剪切板内字符串

        text_raw = get_clipboard()

        print('{0} {1}'.format(text_raw, type(text_raw)))

         

        try:

            text_str = text_raw.decode('utf_8')

            print('{0} {1}'.format(text_str, type(text_str)))

        except:

            print('剪切板为空。')

     

     

     

    剪切板为空时,输出结果为:

    None <class 'NoneType'>

    剪切板为空。

     

    复制一个字符串后运行上面的测试代码(在这里我复制了 python ),输出结果为:

    b'Python' <class 'bytes'>

    Python <class 'str'>

    剪切板中无数据时,get_clipboard() 返回 None。

    当剪切板中有数据时,get_clipboard() 将其以 bytes 格式返回;

    使用 text_str = text_raw.decode('utf_8')将 bytes 转化为 str。

    2、调用 empty_clipboard() 清空剪切板

    1

    2

    3

    4

    5

    if __name__ == '__main__':

        # 清空剪切板

        empty_clipboard()

        text = get_clipboard()

        print(text)复制一个字符串后运行代码,输出结果为:None

    3、调用 set_clipboard() 写入剪切板

    1

    2

    3

    4

    5

    6

    7

    8

    if __name__ == '__main__':

        # 向剪切板内写入 ascii 字符串

        set_clipboard('py!')

        text = get_clipboard()

        print(text)

     

    输出结果为:

    b'py!'

    更多Python知识请关注Python自学网

    专题推荐:python
    上一篇:Python中的字典遍历有序吗? 下一篇:python中css如何定位?

    相关文章推荐

    • 你知道python迭代器和生成器的区别吗?• Python中的浮点数如何计算?• Python怎么把数字变成中文?• Python中的main函数解析

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网