How To Run A Python Script File With A Subprocess.Run Command Through Execute Shell Script

Hello all!

I'm trying to run a python script through the Execute Shell Script action

/usr/local/bin/python3 /Users/mayrc/Desktop/ffmpeg_mp4.py

The python script eventually tries to run a ffmpeg command through subprocess.run(ffmpegCommand), which works perfectly if I run the script from the Terminal.

However, when KM executes the script, I get the error

2022-11-03 10:47:42 Action 11167 failed: Execute a Shell Script failed with script error: Traceback (most recent call last):
File "/Users/mayrc/Desktop/ffmpeg_mp4.py", line 24, in
subprocess.run(shellCommand)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/subprocess.py", line 546, in run
with Popen(*popenargs, **kwargs) as process:
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/subprocess.py", line 1022, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/subprocess.py", line 1899, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
2022-11-03 10:47:42 Execute a Shell Script failed with script error: Traceback (most recent call last):
File "/Users/mayrc/Desktop/ffmpeg_mp4.py", line 24, in
subprocess.run(shellCommand)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/subprocess.py", line 546, in run
with Popen(*popenargs, **kwargs) as process:
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/subprocess.py", line 1022, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/subprocess.py", line 1899, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'. Macro “ffmpeg to mp4” cancelled (while executing Execute Shell Script).

Does KM execute the script somehow "differently" so the python script can run subprocesses, or what else could the issue be? And how can I solve it? I'm running out of ideas ..
Thank you all!

Best regards,
Christian

Looks like the shellCommand variable in your Python script doesn’t contain the full path to ffmpeg. The environment under which shell scripts are run is different in Keyboard Maestro than it is in Terminal. Search for ENV_PATH in the KM wiki.

1 Like

Of course, thank you! I forgot that the subprocess inside the python script also doesn't use the "regular" Terminal shell ... the path has to be included "all the way down". Thanks!

1 Like