python - 在网络应用程序上使用 PyperClip

标签 python pyperclip

我正在使用 pyperclip.py 使用表单在我的网络应用程序中获取电子邮件地址列表,以便用户可以通过剪贴板将其粘贴到本地。它在本地运行完美。然而,当它在服务器(带有 Apache2 的 Linux 14.04)上运行并通过浏览器从客户端系统访问时,它不会复制。如何将其复制到客户端系统的剪贴板?

现在我只是想让它工作,因此我只使用一行。我将 pyperclip 1.5.15 与 xclip 和 Python 3.4 一起使用。服务器运行的是 Linux 14.04,客户端注意到使用 Google Chrome 和 IE 的 Windows 8 和 Windows 10 上存在问题。目前尚未测试其他操作系统。

pyperclip.copy("HELLO") 

最佳答案

由于我找不到有关此主题的许多详细信息,我想我应该回答我的问题。不幸的是,浏览器似乎不支持 pyperclip,因此需要 HTML + Javascript 解决方案(意味着在 pyperclip 上)。首先,将 Django 模板变量添加为 HTML 属性,您可以使用 Javascript 来处理复制功能。下面是如何执行此操作的示例,提前抱歉,因为 stackoverflow 为该示例提供了一些奇怪的格式。它还假设您有一个下面的表单,其 id 为 email_list_clipboard。我希望这对可能遇到类似问题的其他人有所帮助!

示例:

    <html email-list="{{request.session.email_list}}">
    <script>
        $(document).ready(function () {
            function copyTextToClipboard(text) {
                var textArea = document.createElement("textarea");

                // Place in top-left corner of screen regardless of scroll position.
                textArea.style.position = 'fixed';
                textArea.style.top = 0;
                textArea.style.left = 0;

                textArea.style.width = '2em';
                textArea.style.height = '2em';

                // We don't need padding, reducing the size if it does flash render.
                textArea.style.padding = 0;

                textArea.style.border = 'none';
                textArea.style.outline = 'none';
                textArea.style.boxShadow = 'none';

                textArea.style.background = 'transparent';

                textArea.value = text;

                document.body.appendChild(textArea);

                textArea.select();

                try {
                    var successful = document.execCommand('copy');
                    var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copying text command was ' + msg);
                } catch (err) {
                    console.log('Oops, unable to copy');
                }

                document.body.removeChild(textArea);
            }

            // set things up so my function will be called when field_three changes
            $('#email_list_clipboard').click(function (click) {
                event.preventDefault();
                copyTextToClipboard(document.documentElement.getAttribute("email-list"));
    });

</script>

关于python - 在网络应用程序上使用 PyperClip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33260553/

相关文章:

python - 使用 reStructuredText 添加一些具有自定义 "id"和 "class"属性的 HTML

python - NLTK 单词标记除带有破折号的单词外的所有单词,例如 ('hi-there' , 'me-you' )

python - 如何根据模型要求 reshape 我的数据?

python - 使用PyCharm,似乎无法导入Pyperclip模块

python - 如果 x 相同,如何不打印?

python - 没有在 python 中给出所需的输出

python - Scipy 中的高性能计算,具有独立应用于大量输入的数值函数

python - 将 pyperclip 复制到剪贴板与 pyautogui 粘贴相结合?

python - 使用 Pyperclip 复制和粘贴二维数组