首页 > 解决方案 > 粘贴到Python时如何截断回车

问题描述

我创建了一个将复制到系统剪贴板的函数。但是,当我从剪贴板粘贴值时,它会自动执行回车。这极大地影响了我程序中的计算。

注意:不能使用 Pyperclip 或任何其他安装。我只能为此使用 Python IDLE 3.8 中包含的内容

我尝试使用带有 clipboard_answer 变量的 strip() 方法。它仍然返回到下一行

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

假装“|” 图标是光标

我有一个复制到我的剪贴板的解决方案,即 25

当我在程序中按 CTRL+V 时,我希望它会这样做

25 |

但实际上光标是这样的

25

|

标签: pythoncopyclipboardpastecarriage-return

解决方案


不要使用os.system. 使用subprocess,您可以将字符串直接提供给标准输入,clip而无需调用 shell 管道。

from subprocess import Popen, PIPE

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

推荐阅读