How to Run Python (with imported modules) from Applescript => Module Not Found Errors - python-3.x

How do I run a python script (with imported modules) from Applescript?
From terminal, these scripts work fine
python -m api.get_classrooms
python /absolute/path/to/project/api/get_classrooms.py
If I run the terminal script from AppleScript, I get module not found errors:
set pythonPath to "/path/to/anaconda3/envs/jupyter/bin/python"
set scriptPath to "/absolute/path/to/project/api/get_classrooms.py"
set result to do shell script pythonPath & " " & scriptPath & " "
I get the error
ModuleNotFoundError: No module named 'api'"
I did add my project to the $PYTHONPATH within .bash_profile
echo $PYTHONPATH => /path/to/project/a
And the python file (called by AppleScript) is set to executable
Is Applescript not aware of the PYTHONPATH?
Any push in the right direction is appreciated.

AppleScript's do shell script does not import the environment used by a typical interactive shell. This includes the $PATH variable, which I suspect is where your pro blew lies. You can coerce it into doing a full setup by calling the path_helper utility that apps like Terminal use. Try running this code:
set pythonPath to "/path/to/anaconda3/envs/jupyter/bin/python"
set scriptPath to "/absolute/path/to/project/api/get_classrooms.py"
set result to do shell script "eval `/usr/libexec/path_helper -s`; python -m api.get_classrooms"

Thanks to ted wrigley :) I was finally able to get it to work...
By not targeting the get_classrooms.py script directly.
Instead, AppleScript runs the below shell script (working within the project's subdirectory 'bash'. The bash script executes the python script. It wasn't the exact solution I wanted...but it works...and is (perhaps) more elegant....at least until the project is converted to a webapp with flask.
For anyone having trouble targeting python scripts with applescript applescript=>bash=>python
Applescript
do shell script "/Users/me/path/to/project/bash/applescript.sh"
Bash script within project/bash directory
#!/usr/bin/env bash
# eval /usr/libexec/path_helper -s; # didn't need
export PYTHONPATH='/Users/me/path/to/project';
/Users/me/anaconda3/envs/jupyter/bin/python -m api.get_classrooms

Related

How to run a shell script as source using python to set environment variables?

I created a shell script which is used to set the environment variables. I am trying to run this script via a python script but every time shows me error as "Command not found". I want to run the shell script as source for setting up the environment variables.
Python : 2.7.5
Script Name : abc.sh
Normal Execution on shell : source abc.sh
Tried using
python : os.system ("source abc.sh")
this shows an error as
"Command not found".
Anybody can help me out how to run this script successfully as source via python ?
The error is because source is a shell "builtin" command -- it is not an external command in your $PATH. But the more fundamental problem is that what you're trying to do won't work due to how environment variables work.
Env vars are private to each process. They are not global and a process cannot modify the env vars of a different process; at least not without the cooperation of the other process. When you start a process it inherits a copy of the env vars of the parent process or the parent provides an explicit set of env vars to the child process it spawns. In either event each process has its own, private, env vars. So even if you did
os.system("sh -c 'source abc.sh'")
it would only modify the env vars of the sh subprocess. It would not modify the environment of the python process.
The simplest solution is to start a shell, do the source abc.sh, then exec your python program. If you absolutely have to set the env vars by running a shell script from within your python program your script will have to write the vars to stdout. Your python program will then have to read that output and parse it to extract the env vars names and value then call os.putenv() to set each var in the python process.
Try your command in command prompt. This because you have not define os in the your command
python : os.system ("source abc.sh"). Your computer is unable access os.system. You first need to install the packages of python which os.system module in it.

Run SH script in a new terminal window

I am currently using crontab to run a SH script at boot which navigates to the path of my python script, switches to a different python environment and runs my python script, although it works perfectly fine it runs hidden without a terminal for me to monitor whatever the python interpreter prints like errors, how could I make it so the python interpreter points at a newly opened terminal window?
Here is my SH script (runs with the bash interpreter, not sh):
#!/bin/sh
cd /
cd /home/pi/Desktop/Juvia-py
source defenv/bin/activate
python3 juvia.py &
and my crontab entry:
#reboot bash /home/pi/launcher.sh
Thank you
If you just want to record errors, you could pipe STDOUT and STDERR to files, something like
python3 juvia.py >stdout.log 2>stderr.log &
But if you wanted to open it in a separate window so you could interact you would need to manage STDIN more creatively.

python3: How can I run a python script when python starts?

I have a shortcut which runs python3 in a terminal window. I would like to add some import commands to a python script which is to be run when python starts.
How can I do this?
eg; I have xfce4-terminal -e python3 which starts a graphical terminal session with python3 running. I want to add something to this to make python3 execute a script, however I do not want python to exit at the end of the script, which is the default behaviour if a filename is given immediatly following the python3 command.
See python --help. It mentions an environment variable called PYTHONSTARTUP which looks like it could help you get where you want.

Programmatically running a shell script in matlab

I am trying to open a terminal and run a script using matlab. The script will open an ssh connection. The matlab command is:
system(['lxterminal -e "bash ' scriptName '" &'],'-echo');
When I execute the matlab command the script runs but fails fails to validate SSL credentials.
The script is running ssh through the python paramiko package.
The error arises from the cli.py module.
The problem is solved if I run
system(['lxterminal -e "sudo bash ' scriptName '" &'],'-echo');
but then I have to enter the user password each time I execute the script.
If I open an lxterminal and run the same command:
bash scriptName
it works without the sudo.
I think it is related to some environmental variables / configuration which are not loaded in lxterminal before running the script, but cannot figure out it.
Using xterm instead of lxterminal has the same behavior.
Any ideas?
The fix, might be dirty, was to empty the LD_LIBRARY_PATH from the matlab environmental variables before calling the system command using the following command in the matlab script
setenv('LD_LIBRARY_PATH');
Probably the matlab LD_LIBRARY_PATH path is using obsolete libraries compared to the ones python needs.
A better approach might be to start removing one by one the paths until finding the one causing the problem.

Anaconda activate

I am using anaconda python. So every time, in my mac terminal, I input the terminal command:
source /Users/mylaptop/anaconda/bin/activate /Users/mylaptop/anaconda
And then I activated the anaconda python environment. But I don't want to write this command line every time, so I tried a bash script like this:
#! /bin/bash
source /Users/mylaptop/anaconda/bin/activate /Users/mylaptop/anaconda
and I put this file in the directory /usr/local/bin. But unfortunately, I cannot log into anaconda environment in this way. There is no error message showed up in the terminal. So I do not know what is happening here.
Could anyone help me out?
The easiest fix is to just put /Users/mylaptop/anaconda in your PATH, by adding something like
export PATH="/Users/mylaptop/anaconda:$PATH"
to your bash profile (~/.profile).
You can't put the activate script in a script because it has to be "sourced" to work. source causes the script to be run in your current shell (as opposed to a subshell, which is how the bash script you wrote is run). This is necessary because it modifies your PATH environment variable, and environment variables from your current shell cannot be modified by subshells.

Resources