I have a Python program that I'm porting to Mac. I need to load a saved image file into the clipboard so that it can be pasted into a document using cmd + v.
This was the closest thread to what I need but the solutions don't work because my osascript filepath is unknown. It is a variable defined in Python by the user and I'm struggling with syntax necessary to pass the variable from Python to osascript.
This doesn't work:
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 prints as: /Users/admin/Desktop/PROGRAMMING which is the correct path but it results in "execution error: Can’t make file ":+ str(inpath) + :tc.jpg" into type file. (-1700)"
Nor does this:
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)'])
It results in: "syntax error: Expected “,” but found “"”. (-2741)"
The following:
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)'])
Results in: "SyntaxError: EOF while scanning triple-quoted string literal"
Any help would be greatly appreciated!
EDIT: Updated code below:
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)" ])
Now returns: "NameError: name 'inpath' is not defined"
EDIT 2: Completes without error but fails to load to clipboard.
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()
This returns no errors and prints correct path but does not add the file to the clipboard.
You have likely got a linefeed at the end of your string inpath
, so try:
inpath = line[2].strip('\n')
Then you want:
subprocess.run(["osascript", "-e", "set the clipboard to (read (POSIX file \"" + inpath + "/tc.jpg\") as JPEG picture)" ])