[英]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.