简体   繁体   English

粘贴到Python中时如何截断回车

[英]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. 注意:不能使用Pyperclip或任何其他安装。 I can only use what's included in Python IDLE 3.8 for this 我只能使用Python IDLE 3.8中包含的功能

I've tried using the strip() method with the clipboard_answer variable. 我试过将strip()方法与剪贴板_answer变量一起使用。 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, ie 25 我有一个解决方案已复制到剪贴板,即25

When I CTRL+V in the program I expect it to do this 当我在程序中按CTRL + V时,我希望它能够执行此操作

25 | 25 |

But in actuality, the cursor is like this 但是实际上,光标是这样的

25 25

| |

Don't use os.system . 不要使用os.system Use subprocess , and you can feed the string directly to the standard input of clip without invoking a shell pipeline. 使用subprocess ,您可以将字符串直接输入到clip的标准输入,而无需调用shell管道。

from subprocess import Popen, PIPE

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

pyperclip.copy(solution)

This should do the trick. 这应该可以解决问题。

EDIT: The tkinter solution again since pyperclip is no option for OP. 编辑:tkinter解决方案再次,因为pyperclip是OP的选项。

from tkinter import Tk

r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append("hello world")
r.update()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM