Search code examples
pythoncopyclipboardpastecarriage-return

How to truncate carriage return when pasting into Python


I created a function that will copy to the system clipboard. However, when I paste the value from the clipboard, it automatically does a carriage return. This drastically affects calculations in my program.

Note: Cannot Use Pyperclip or any other installation. I can only use what's included in Python IDLE 3.8 for this

I've tried using the strip() method with the clipboard_answer variable. It still returns to the next line

def copy(solution_answer): 
    clipboard_answer = str(solution_answer)
    command = 'echo ' + clipboard_answer.strip() + '| clip' # Creates command variable, then passes it to the os.system function as an argument. CMD opens and applys echo (number calculated) | clip and runs the clipboard function
    os.system(command)
    print("\n\n\n\n",solution_answer, "has been copied to your clipboard") # Used only for confirmation to ensure copy function runs

Pretend the "|" icon is the cursor

I have a solution that was copied to my clipboard, i.e. 25

When I CTRL+V in the program I expect it to do this

25 |

But in actuality, the cursor is like this

25

|


Solution

  • Don't use os.system. Use subprocess, and you can feed the string directly to the standard input of clip without invoking a shell pipeline.

    from subprocess import Popen, PIPE
    
    Popen(["clip"], stdin=PIPE).communicate(bytes(solution_answer))