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

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

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

This was the closest thread to what I need 但解决方案不起作用,因为我的 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 这是正确的路径,但它导致 "execution error: Can’t make file ":+ 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)'])

结果为:"syntax error: Expected “,” but found “"”。 (-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)'])

结果:"SyntaxError: EOF while scanning triple-quoted string literal"

如有任何帮助,我们将不胜感激!

编辑:更新了以下代码:



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)" ])

现在returns:"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()

这 returns 没有错误并打印出正确的路径,但没有将文件添加到剪贴板。

您的字符串末尾可能有换行符 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

ONLY 读取标准输入。例如

猫image.jpg | pbcopy