簡體   English   中英

粘貼到Python中時如何截斷回車

[英]How to truncate carriage return when pasting into Python

我創建了一個將復制到系統剪貼板的函數。 但是,當我從剪貼板粘貼值時,它將自動執行回車。 這極大地影響了我程序中的計算。

注意:不能使用Pyperclip或任何其他安裝。 我只能使用Python IDLE 3.8中包含的功能

我試過將strip()方法與剪貼板_answer變量一起使用。 它仍然返回到下一行

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

|

不要使用os.system 使用subprocess ,您可以將字符串直接輸入到clip的標准輸入,而無需調用shell管道。

from subprocess import Popen, PIPE

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

pyperclip.copy(solution)

這應該可以解決問題。

編輯: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