我有一个要移植到 Mac 的 Python 程序。我需要将保存的图像文件加载到剪贴板,以便可以使用 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) + :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)'])
结果:“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)" ])
现在返回:“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)" ])
关于python - 需要一种使用 Python 将图像文件加载到 Mac 剪贴板的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58281361/