繁体   English   中英

需要一种使用 Python 将图像文件加载到 Mac 剪贴板的方法

[英]Need a way to load image file into Mac clipboard using Python

我有一个要移植到 Mac 的 Python 程序。 我需要将保存的图像文件加载到剪贴板中,以便可以使用 cmd + v 将其粘贴到文档中。

这是最接近我需要的线程,但解决方案不起作用,因为我的 osascript 文件路径未知。 它是用户在 Python 中定义的一个变量,我正在努力使用将变量从 Python 传递到 osascript 所需的语法。

这不起作用:

import subprocess


def imagepath():                               
    f=open('config.txt')
    line=f.readlines()
    inpath = (line[2])    
    print(inpath)
    return(inpath)

imagepath()

subprocess.run(["osascript", "-e", 'set the clipboard to (read (POSIX file  "+ str(inpath) + /tc.jpg") as JPEG picture)'])

inpath 打印为: /Users/admin/Desktop/PROGRAMMING 这是正确的路径,但会导致“执行错误:无法将文件“:+ str(inpath)+:tc.jpg”转换为类型文件。(-1700 )"

这也不是:

import subprocess


def imagepath():                               
    f=open('config.txt')
    line=f.readlines()
    inpath = (line[2])    
    print(inpath)
    return(inpath)

imagepath()

subprocess.run(["osascript", "-e", 'set the clipboard to (read (POSIX file  """+ str(inpath) + /tc.jpg""") as JPEG picture)'])

它导致:“语法错误:应为“,”但找到“”。 (-2741)"

以下:

import subprocess


def imagepath():                                 # check line 1 of config file (screencap name)
    f=open('config.txt')
    line=f.readlines()
    inpath = (line[2])    # note: confusing.  0=line 1, 1=line2 etc.
    print(inpath)
    return(inpath)

imagepath()

subprocess.run(["osascript", "-e", 'set the clipboard to (read (POSIX file  ''' + str(inpath) + '''/tc.jpg") as JPEG picture)'])

结果:“语法错误:扫描三引号字符串时出现 EOF”

任何帮助将不胜感激!

编辑:更新代码如下:



def imagepath():                                 # check line 1 of config file (screencap name)
    f=open('config.txt')
    line=f.readlines()
    inpath = line[2].strip('\n')
    print(inpath)
    return(inpath)

imagepath()

subprocess.run(["osascript", "-e", "set the clipboard to (read (POSIX file \"" + inpath  + "/tc.jpg\") as JPEG picture)" ])

现在返回:“NameError: name 'inpath' is not defined”

编辑 2:完成没有错误,但无法加载到剪贴板。

import subprocess


def imagepath():                                 # check line 1 of config file (screencap name)
    f=open('config.txt')
    line=f.readlines()
    inpath = (line[2]).strip('\n')
    print(inpath)
    return(inpath)
    subprocess.run(
        ["osascript", "-e", "set the clipboard to (read (POSIX file \"" + inpath + "/tc.jpg\") as JPEG picture)"])
imagepath()

这不会返回错误并打印正确的路径,但不会将文件添加到剪贴板。

您可能在字符串inpath的末尾有换行符,因此请尝试:

inpath = line[2].strip('\n')

然后你想要:

subprocess.run(["osascript", "-e", "set the clipboard to (read (POSIX file \"" + inpath  + "/tc.jpg\") as JPEG picture)" ])

Mac为此提供了一个命令行实用程序:

pbcopy

只读取标准输入。例如

猫图片.jpg | pbcopy

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM