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

2024-09-28 21:45:01 发布

您现在位置: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,这是正确的路径,但会导致“执行错误:无法生成文件”:+str(inpath)+:技术合作伙伴“”转换为类型文件。(-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)'])

结果为:“SyntaxError: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:名称'inpath'未定义”

编辑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()

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


Tags: 文件thetotxtconfigdeflineopen
1条回答
网友
1楼 · 发布于 2024-09-28 21:45:01

您的字符串inpath的末尾可能有一个换行符,请尝试:

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

然后你想:

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

相关问题 更多 >