复制字符串 - Python [英] Copy string - Python
问题描述
好吧,我想象这很容易,但我似乎无法找到如何复制字符串。
Ok guys I imagine this is easy but I can't seem to find how to copy a string. Simply COPY to the system like CTRL+C on a text.
基本上我想复制一个字符串,所以我可以让我们说,粘贴(ctrl + v) 。
Basically I want to copy a string so I can for example, lets say, paste(ctrl+v).
对于这样一个琐碎的问题,哈哈。
Sorry for such a trivial question, haha.
推荐答案
这取决于很多的操作系统。在Linux上,由于X的奇异选择模型,最简单的方法是使用 popen('xsel -pi')
,并将文本写入该管道。
This depends a lot on the OS. On Linux, due to X's bizarre selection model, the easiest way is to use popen('xsel -pi')
, and write the text to that pipe.
例如:(我认为)
def select_xsel(text):
import subprocess
xsel_proc = subprocess.Popen(['xsel', '-pi'], stdin=subprocess.PIPE)
xsel_proc.communicate(some_text)
正如评论中所指出的,在Mac上,您可以使用 / usr / bin / pbcopy
命令,如下所示:
As pointed out in the comments, on a Mac, you can use the /usr/bin/pbcopy
command, like this:
xsel_proc = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
如果要支持不同的操作系统,可以将 os.name
以确定要使用的方法:
If you want to support different OSes, you could combine different solutions with os.name
to determine which method to use:
import os, subprocess
def select_text(text):
if os.name == "posix":
# try Mac first
try:
xsel_proc = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
except:
# try Linux version
xsel_proc = subprocess.Popen(['xsel', '-pi'], stdin=subprocess.PIPE)
elif os.name == "nt":
# Windows...
这篇关于复制字符串 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!