我试图使一个基本的Windows应用程序构建出用户输入的字符串,然后将其添加到剪贴板。如何使用Python将字符串复制到剪贴板?
当前回答
我认为有一个更简单的解决办法。
name = input('What is your name? ')
print('Hello %s' % (name) )
然后在命令行中运行程序
Python greeting .py |剪辑
这将把文件的输出输出到剪贴板
其他回答
使用pyperclip模块
使用pip安装pyperclip。
https://pypi.org/project/pyperclip/
复制文本“Hello World!”到剪贴板
import pyperclip
pyperclip.copy('Hello World!')
你可以在任何地方使用Ctrl+V来粘贴它。
使用python粘贴复制的文本
pyperclip.paste() # This returns the copied text of type <class 'str'>
最简单的方法是用pyperclip。适用于python 2和3。
要安装这个库,请使用:
pip install pyperclip
使用示例:
import pyperclip
pyperclip.copy("your string")
如果你想获取剪贴板的内容:
clipboard_content = pyperclip.paste()
我在这里分享的代码片段利用了格式化文本文件的功能:如果您想将复杂的输出复制到剪贴板,该怎么办?(比如一个列中的numpy数组或一个列表)
import subprocess
import os
def cp2clip(clist):
#create a temporary file
fi=open("thisTextfileShouldNotExist.txt","w")
#write in the text file the way you want your data to be
for m in clist:
fi.write(m+"\n")
#close the file
fi.close()
#send "clip < file" to the shell
cmd="clip < thisTextfileShouldNotExist.txt"
w = subprocess.check_call(cmd,shell=True)
#delete the temporary text file
os.remove("thisTextfileShouldNotExist.txt")
return w
只适用于windows,我猜可以适用于linux或mac。可能有点复杂……
例子:
>>>cp2clip(["ET","phone","home"])
>>>0
在任何文本编辑器中按Ctrl+V:
ET
phone
home
你也可以使用>剪贴板
import clipboard
def copy(txt):
clipboard.copy(txt)
copy("your txt")
看起来您需要将win32clipboard添加到站点包中。它是pywin32包的一部分
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 如何运行一个PowerShell脚本而不显示窗口?