How do I copy a string to the clipboard on Windows using Python?

后端 未结 23 3305
温柔的废话
温柔的废话 2020-11-22 03:13

I\'m trying to make a basic Windows application that builds a string out of user input and then adds it to the clipboard. How do I copy a string to the clipboard using Pytho

23条回答
  •  情书的邮戳
    2020-11-22 03:39

    The snippet I share here take advantage of the ability to format text files: what if you want to copy a complex output to the clipboard ? (Say a numpy array in column or a list of something)

    import subprocess
    import os
    
    def cp2clip(clist):
    
        #create a temporary file
        fi=open("thisTextfileShouldNotExist.txt","w")
    
        #write in the text file the way you want your data to be
        for m in clist:
            fi.write(m+"\n")
    
        #close the file
        fi.close()
    
        #send "clip < file" to the shell
        cmd="clip < thisTextfileShouldNotExist.txt"
        w = subprocess.check_call(cmd,shell=True)
    
        #delete the temporary text file
        os.remove("thisTextfileShouldNotExist.txt")
    
        return w
    

    works only for windows, can be adapted for linux or mac I guess. Maybe a bit complicated...

    example:

    >>>cp2clip(["ET","phone","home"])
    >>>0
    

    Ctrl+V in any text editor :

    ET
    phone
    home
    

提交回复
热议问题