Apple Event: May 7th at 7 am PT

Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Running Python in Automator

I am trying to make a pic to text code for Python. I run it in Atom(compiler) and it works fine. I run it in Terminal and it runs fine, but I'm trying to do it in automator but it isn't working. Here's the error:


User uploaded file

macOS High Sierra (10.13.2)

Posted on Mar 11, 2018 9:38 AM

Reply
34 replies

Mar 11, 2018 11:43 AM in response to VikingOSX

Ok so I'm having the screenshot save the picture file in Documents(where my PicToText.py is) and then as soon as that's done I want to have the Python Code to run. (So do I use arguments or stdin). Sorry I am so new to this I've had Mac for a few days but want to get this working. So then after I change that setting what will I enter into the ShellScript? Here is my code:


User uploaded file

Mar 11, 2018 1:23 PM in response to rccharles

An Applescript to show user info.


(*

It is easier to diagnose problems with debug information. I suggest adding
log statements to your script to see what is going on.  Here is an example.


    Author: rccharles

    For testing, run in the Script Editor.
      1) Click on the Event Log tab to see the output from the log
          statement
      2) Click on Run
   
  For running shell commands see:
  http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html



*)


on run
    -- Write a message into the event log.
    log "  --- Starting on " & ((current date) as string) & " --- "
    --  debug lines
    set desktopPath to (path to desktop) as string
    log "desktopPath = " & desktopPath

    set unixDesktopPath to POSIX path of desktopPath
    log "unixDesktopPath = " & unixDesktopPath

Here is an applescript to display some system info.
    set quotedUnixDesktopPath to quoted form of unixDesktopPath
    log "quoted form is " & quotedUnixDesktopPath

    try
        set fromUnix to do shell script "pwd  "
        display dialog "pwd " & return & fromUnix giving up after 7
        set fromUnix to do shell script "id "
        display dialog "id " & return & fromUnix giving up after 7
     
     
        set fromUnix to do shell script "ls -l  " & quotedUnixDesktopPath
        display dialog "ls -l of " & quotedUnixDesktopPath & return & fromUnix giving up after 10
    on error errMsg
        log "ls -l error..." & errMsg
    end try

end run




User uploaded file


User uploaded file


Third display not recorded.

Mar 11, 2018 11:35 AM in response to mmodi1

Because it is using the default system PATH, and not yours, so it cannot find the Python program. My .bash_profile has a custom PATH statement in it that also includes my $HOME directory, and current (.) directory. You may have to still use ./PicToText.py to force it to look in the Documents folder for that script — or its full path.


Also, if your Python program is written to get ARGV elements passed in from the previous action, then change the pass input to Arguments. If you are using the Python fileinput module to slurp standard input, then leave the current setting to stdin.


(cd ~/Documents; source ~/.bash_profile; python -d -c PicToText.py) > ~/Desktop/PicToText.log

Mar 11, 2018 1:25 PM in response to mmodi1

Do not use any ~ in your scripts. Your not running were you think.


Use all explicit paths. Of course, this is a make it work approach. run the id command to see what is going on.


I suggest you first debug this in an actual applescript. It could be that any time a shell command get an error your applescript quits. I think so. See my applescript in the next post for catching errors.


R

Mar 11, 2018 1:51 PM in response to mmodi1

Set the Run Shell Script Shell back to /bin/bash, or it will not understand some of the shell syntax here. Also, what is going on with the Automator action that precedes your Run Shell Script? The double ampersand is saying do the following if the result of cd ~/Documents is successful.


(cd ~/Documents && /usr/bin/python -d -c ./PicToText.py) &> ~/Desktop/scriptlog.txt

Mar 11, 2018 2:48 PM in response to VikingOSX

It's taking a certain screenshot to a .png file that the python code will then take and turn into text. That part is working fine. Ok so i did

(cd ~/Documents && /usr/bin/python -d -c ./PicToText.py) &> ~/Desktop/scriptlog.txt


and now all its telling me is "The action "Run Shell Script" encountered an error." and thats it. Its not telling me what or where the problem is.

Mar 11, 2018 4:22 PM in response to mmodi1

For what it's worth, I got this to work. I ran it from within applescript. The process wasn't without a little pain, so you will see some simplifications.


You can see that I simplified what goes to the command line. I have the output be returned directly to applescript. Simplify to get things to work, then add things back if needed.


(*

It is easier to diagnose problems with debug information. I suggest adding
log statements to your script to see what is going on.  Here is an example.


    Author: rccharles

    For testing, run in the Script Editor.
      1) Click on the Event Log tab to see the output from the log
          statement
      2) Click on Run

  For running shell commands see:
  http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html



*)


on run


    try
        set fromUnix to do shell script "pwd  "
        log "pwd " & return & fromUnix
        set fromUnix to do shell script "id "
        log "id " & return & fromUnix
        -- /usr/bin/python -d -c
        -- > ~/Desktop/scriptlog.txt
   
        set toUnix to "cd ~/Documents  &&   ~/config/PicToText.py  "
        set fromUnix to do shell script toUnix
        log "first fromUnix is: " & fromUnix
   
   
    on error errMsg
        log "  error..." & errMsg
    end try

end run




You can see I added where to run python on the script. I could not get the -c option to work. Should you not want to modify the script, you can always put a unix ln command where ever the script thinks it should be.


#! /usr/bin/python

print("Hello, World from python!!!")



mac $
mac $ ls -l PicToText.py
-rwxr-xr-x@ 1 mac  staff    56B Mar 11 19:05 PicToText.py*
mac $

Mar 11, 2018 4:39 PM in response to rccharles

I believe the reason -c didn't work is that the -c option is expecting a valid python code. Passing the location of the python script isn't valid python.


See: Medhat Helmy answer for how to call a python script from python code. It got fewer points, but is the more current answer, I think.

Run a python script from another python script, passing in args - Stack Overflow

Mar 12, 2018 4:24 AM in response to rccharles

The -c option to Python is telling Python to look for a valid script, or quoted inline Python command. Python could care less about the path associated with the script name — provided that the path, and script are valid, and the latter is without internal syntax errors.


The OP's code is currently not written to receive arguments from stdin, or ARGV (command-line) passed into it from a preceding action.


My scripts all have the #!/usr/bin/python, or #!/usr/bin/env python (if multiple Python versions) as the first line and are marked executable so that -c is not required to run the script.


The syntax that I provided, and shown below — works without error when I substitute one of my own Python scripts in the Automator Run Shell Script action. The following is all one line, and I personally never use the -d switch:


(cd ~/Documents && /usr/bin/python -d -c ./PicToText.py) &> ~/Desktop/scriptlog.txt

Mar 12, 2018 5:46 PM in response to mmodi1

I get the same error when I run this script in Yosemite and High Sierra.


(* 

It is easier to diagnose problems with debug information. I suggest adding 
log statements to your script to see what is going on.  Here is an example.


    Author: rccharles
    
    For testing, run in the Script Editor.
      1) Click on the Event Log tab to see the output from the log 
          statement
      2) Click on Run
      
  For running shell commands see:
  http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html
    


 *)


on run
    
    
    
    set fromUnix to do shell script "pwd  "
    log "pwd " & return & fromUnix
    set fromUnix to do shell script "id "
    log "id " & return & fromUnix
    set fromUnix to do shell script "python -V"
    log "python " & return & fromUnix
    set fromUnix to do shell script " /bin/ls -l  /"
    log "ls " & return & fromUnix
    set fromUnix to do shell script "/bin/ls -l  /Users/rmac/"
    log "ls " & return & fromUnix
    set fromUnix to do shell script "/bin/ls -l ~/Documents/PicToText.py"
    log "ls " & return & fromUnix
    try
        -- /usr/bin/python -d -c
        -- > ~/Desktop/scriptlog.txt
        log "trying PicToText.py"
        set toUnix to "(cd ~/Documents && /usr/bin/python -d -c '~/Documents/PicToText.py') &> ~/Desktop/scriptlog.txt "
        set fromUnix to do shell script toUnix
        log "first fromUnix is: " & fromUnix
        
        
    on error errMsg
        log "  error..." & errMsg
    end try
    set fromUnix to do shell script "/bin/cat  ~/Documents/PicToText.py"
    log "cat " & return & fromUnix
    set fromUnix to do shell script "/bin/cat   ~/Desktop/scriptlog.txt "
    log "cat " & return & fromUnix
end run



(*pwd 
/*)
(*id 
uid=501(rmac) gid=20(staff) groups=20(staff),12(everyone),61(localaccounts),79(_appserverusr),80(admin),81(_appserveradm),98(_lpadmin),33(_appstore),100(_lpoperator),204(_developer),250(_analyticsusers),395(com.apple.access_ftp),398(com.apple.access_screensharing),399(com.apple.access_ssh),701(1)*)
(*python 
*)
(*ls 
total 45
drwxrwxr-x+ 39 root  admin  1326 Mar 12 19:34 Applications
drwxr-xr-x+ 62 root  wheel  2108 Mar 12 19:36 Library
drwxr-xr-x@  2 root  wheel    68 Oct  2 20:33 Network
drwxr-xr-x@  4 root  wheel   136 Jan 19 02:18 System
drwxr-xr-x   5 root  admin   170 Feb 21 16:21 Users
drwxr-xr-x@  7 root  wheel   238 Mar 12 20:12 Volumes
drwxr-xr-x@ 38 root  wheel  1292 Jan 19 02:22 bin
drwxrwxr-t@  2 root  admin    68 Oct  2 20:33 cores
dr-xr-xr-x   3 root  wheel  4339 Mar 12 19:21 dev
lrwxr-xr-x@  1 root  wheel    11 Feb 20 21:30 etc -> private/etc
dr-xr-xr-x   2 root  wheel     1 Mar 12 19:43 home
-rw-r--r--@  1 root  wheel   313 Oct  4 17:05 installer.failurerequests
dr-xr-xr-x   2 root  wheel     1 Mar 12 19:43 net
drwxr-xr-x@  6 root  wheel   204 Feb 20 21:31 private
drwxr-xr-x@ 63 root  wheel  2142 Feb 20 21:31 sbin
lrwxr-xr-x@  1 root  wheel    11 Feb 20 21:30 tmp -> private/tmp
drwxr-xr-x@  9 root  wheel   306 Jan 19 02:13 usr
lrwxr-xr-x@  1 root  wheel    11 Feb 20 21:31 var -> private/var*)
(*ls 
total 0
drwx------+  8 rmac  staff   272 Mar 12 20:21 Desktop
drwx---r-x+  9 rmac  staff   306 Mar 12 20:27 Documents
drwx------+  6 rmac  staff   204 Mar 12 19:34 Downloads
drwx------@ 54 rmac  staff  1836 Mar  5 14:42 Library
drwx------+  3 rmac  staff   102 Feb 21 16:21 Movies
drwx------+  3 rmac  staff   102 Feb 21 16:21 Music
drwx------+  3 rmac  staff   102 Feb 21 16:21 Pictures
drwxr-xr-x+  4 rmac  staff   136 Feb 21 16:21 Public*)
(*ls 
-rwxrwxrwx@ 1 rmac  staff  56 Mar 11 18:05 /Users/rmac/Documents/PicToText.py*)
(*trying PicToText.py*)
(*  error...The command exited with a non-zero status.*)
(*cat 
#! /usr/bin/python

print("Hello, World from python!!!")*)
(*cat 
  File "<string>", line 1
    ~/Documents/PicToText.py
     ^
SyntaxError: invalid syntax*)

Mar 12, 2018 6:06 PM in response to rccharles

This works for me. I run it from applescript editor. Worked in 10.10.5.


(*

It is easier to diagnose problems with debug information. I suggest adding
log statements to your script to see what is going on.  Here is an example.


    Author: rccharles

    For testing, run in the Script Editor.
      1) Click on the Event Log tab to see the output from the log
          statement
      2) Click on Run

  For running shell commands see:
  http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html



*)


on run
    
    
    try
        set toUnix to "ls -l ~/Documents/PicToText.py  "
        set fromUnix to do shell script toUnix
        log "fromUnix ls is: " & fromUnix
        set toUnix to "cat ~/Documents/PicToText.py  "
        set fromUnix to do shell script toUnix
        log "fromUnix cat is: " & fromUnix
        
        
        set toUnix to "cd ~/Documents  &&   ./PicToText.py  "
        set fromUnix to do shell script toUnix
        log "fromUnix run icToText.py is: " & fromUnix
        
        
    on error errMsg
        log "  error..." & errMsg
    end try
    
end run




(*fromUnix ls is: -rwxr-xr-x@ 1 mac  staff  56 Mar 11 19:05 /Users/mac/Documents/PicToText.py*)
(*fromUnix cat is: #! /usr/bin/python

print("Hello, World from python!!!")*)
(*fromUnix run icToText.py is: Hello, World from python!!!*)



#! /usr/bin/python

print("Hello, World from python!!!")

Mar 14, 2018 8:42 AM in response to mmodi1

Well, that's progress. It's been slow I'll say.


but it didn't change my HellowWorld.txt file like it shouldve.

I'd like to say the obvious. 😕

Well, I don't have enough information to comment on why. We need to debug it. I cannot believe this is the first thing I learned when programming. Put in print statements. It's hard to believe we are still doing this.


You need to put in print statement each step of the way. I leave in the print statement even after the code is "working". Would help if you posted the code. You can post in at pastebin.com if posting here gives you troubles.


How to post code.


click on Use advanced editor. It's just above the reply box to the far right of the reply box.


click on the blue >>. It's next to the smiling face.


click on syntax highlighting.


click on plain




This will open a little box. Drop your code in to this box.

Mar 14, 2018 12:32 PM in response to mmodi1

Hello


For your original python code, you may simply try the following automator workflow of single run shell script action. Note that there should not be used -c option in python invocation in this case.



1) Run Shell Script action


shell = /bin/bash

pass input = arguments or stdin (not relevant)

code = as follows:


#!/bin/bash source ~/.bash_profile cd ~/Documents || exit python -d PicToText.py




---

For a little more general code processing arguments, you might try something like the following as python script:



#!/usr/bin/python # coding: utf-8 # # file: # PicToText.py # # function: # OCR image to text # # usage # PicToText.py file [file ...] # # output file is named after input file's basename without extension followed by '.txt' # e.g., file.png is OCR'ed and resulting text is saved in file.txt in the same directory as input # import sys, os import pytesseract from PIL import Image for f in [ a.decode('utf-8') for a in sys.argv[1:] ]: t = pytesseract.image_to_string(Image.open(f)) g, e = os.path.splitext(f) with open(g + '.txt', 'w') as f1: f1.write(t.encode('utf-8'))



And the following workflow of two acitons:


1) Run AppleScript action


code = as follows:


choose file with multiple selections allowed




2) Run Shell Script action


shell = /bin/bash

pass input = arguments

code = as follows:


#!/bin/bash source ~/.bash_profile cd ~/Documents || exit python -d PicToText.py "$@"



Good luck,

H

Running Python in Automator

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.