Running Python Script from AppleScript - python

I've installed the cryptography module using pip:
pip install cryptography
Running a simple test.py file with just an import statement, I can confirm that the module is installed. From terminal:
TEST.PY FILE (just one line):
from cryptography.fernet import Fernet
RUNNING FROM TERMINAL:
/usr/local/bin/python3.9 test.py
But when I try to run this script from an Apple Script application, the module cannot be found even though I'm using the same version of python:
RUNNING FROM APPLE SCRIPT:
do shell script "/usr/local/bin/python3.9 test.py"
Any advice would be greatly appreciated. Thanks.

do shell script does not set the working directory so either set it at the start of the shell script:
do shell script "cd \"$HOME\" && /usr/local/bin/python3.9 test.py"
or supply the full path to the test.py script:
do shell script "/usr/local/bin/python3.9 " & quoted form of "/Users/foo/test.py"

I think the difference in execution between Terminal and do shell script is due to the fact that they use different shells. In order for the modules to be found, the $PATH environment variable must contain the path to the /Library/Frameworks/Python.framework/Versions/3.9/bin directory.
You can check what $PATH contains by running the echo $PATH command. At least for me, this variable in Terminal contains the path /Library/Frameworks/Python.framework/Versions/3.9/bin, but in do shell script it does not. One solution might be to add this path to the $PATH. Note that this addition will be persistent only within the current do shell script command.
I haven't tested, try it yourself. Just in case, I also replaced the path to python3.9 with the real one (instead of an alias):
set pathEnvironmentVariable to do shell script "echo $PATH"
if pathEnvironmentVariable does not contain "/Library/Frameworks/Python.framework/Versions/3.9/bin:" then
do shell script "
export PATH=/Library/Frameworks/Python.framework/Versions/3.9/bin:$PATH;
/Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9 " & quoted form of "/Users/foo/test.py"
end if

Go into your Terminal and start your normal Python. Then import your package and see where it is being imported from:
import cryptography
import sys
# Which Python am I running?
print(sys.executable)
# Where is it looking for modules?
print(sys.path)
# Where was cryptography module found?
print(cryptography.__file__)
Now you know how the proper import works.
Then go into the environment it doesn't work, i.e. Applescript and run a script that shows:
which Python it is running, and
where it is importing from
import sys
# Which Python am I using?
print(sys.executable)
# Where does this Python look for modules
print(sys.path)

Related

How to make the equivallent of .bat for mac and how to install python libraries on mac

I have this file.py:
import os
os.system("pip install pip")
os.system("pip install selenium")
How do I make it work for MAC and what is te equivallent of a .bat file in MAC to execute the file.py.
Your file.py script will generally work fine on Mac as long as the environment the script is running in is set up right. Most notably, the pip executable has to be findable via the current PATH variable. You might benefit by looking at the subprocess module, which is an alternative API for running external commands. It is a more robust mechanism for doing so.
The equivalent of a .BAT file is a shell script. You have a choice as to which shell to use to run the script. I think the most common source is the Bash shell. It is often the case that you use whatever shell is running at your command prompt. This functionality is generally much more general and flexible than a .BAT file is on Window. See this link for a discussion of many of the issues:
https://developer.apple.com/library/archive/documentation/OpenSource/Conceptual/ShellScripting/shell_scripts/shell_scripts.html
A shell script can just be one or more commands that you might run in your Terminal. For example, to run test.py at a Terminal prompt, you'd do this:
> python test.py
The simplest equivalent in a shell script would be the same thing:
python test.py
A script that looks like this is run by whatever shell executes the shell script. What is more usually done is that a "shebang" line is added to the top of the shell script to explicitly define which shell will be used to run the script. So what the single line script above should really look like is this:
#!/bin/sh
python test.py
This may be starting to make your head spin. I would suggest reviewing the link I gave above, and possibly reviewing some other materials that explain shell scripts. Note that nothing about shell scripts is unique to the Mac. The concept is exactly the same on Linux, Unix, etc.
BTW, do you really want pip install pip? What does that do? Doesn't the pip package have to already be installed if the pip command is working?

Python3 as default python version

I am creating a script that will call an API and return some results. I have the script working with pycharm on my computer but I am running into a few problems but I want to focus on this problem first.
1) I am unable to set Python3 as my default python.
I am using a Mac. When I go into terminal I enter $ python --version and it returns Python 2.7.10
I then enter $ alias python=python3, and when I run $python --version it returns Python 3.7.2
When I create a py.script with the os module, it does not work. See my code below.
import os
os.system('alias python=python3')
print(os.system('python --version')
It prints 2.7.10
I also tried to run the os.system('alias python="python3"')
On -nix machines (including OSX), one way to change the version of the interpreter that the script runs with is to add a shebang as the first line of your script.
Eg.
#! /usr/bin/env python3
import sys
print(sys.version)
Then to run your script do:
~/$ chmod u+x myscript.py
~/$ ./myscript.py
You only need to run the chmod command the first time. It enables you to execute the file. Whenever you run your script directly (rather than as an argument to python) your script will be run using the version specified by the shebang.
welcome to SO! Pycharm needs you to specify which interpreter to use as default, as it wouldn't choose the system one by default.
So if you want python3, you can run which python3, and use the path as a settings for the current project. How to do that step by step is here:
https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html
Hope it help, post a comment if you need more details.
This isn't surprising, because os.system opens its own shell, and running alias in that way only affects the currently running terminal. Each call to os.system would be in a separate shell.
I'm not sure what your ultimate goal is, but you almost certainly don't need to change what python means to a shell to do it. If you DO, you'll have to run both commands at once.
import subprocess
cp = subprocess.run("alias python=python3 && /path/to/script")
Interesting - apparently os.system ignores the alias? Just checked it in Linux and got the same results.
Try sys instead of os:
import sys
print(sys.version)

How to execute python3 program in shell script

I have a python program which I need to run at a particular day of a month, so I am using crontab for this task and create a shell script to run this python program.
This is part of my shell script:
#!/bin/bash
filepath='file2018'
cd ${filepath}
python3 file.py
When I run the crontab which executes the shell script, the log file shows the following error:
line 9: python3: command not found
I'm really confused about why this error occurs because I have already install python3 and I can run python3 directly from the command line.
Besides, if I replace python3 with python, the shell script works! My python version is python2, but I have to use python3 for this program, so I have to use python3 instead of python.
My operating system is Linux CentOS.
Hope someone can give me some tips!
You can give the full path to the python3 executable. You can get it using the which python3 command. Try it out.
in file.py add first line like below and add +x permission to file.py file
#!/usr/bin/python3
it will automatically execute, no need to mention python3 in the script
use "which python3" command to know exact path of python3 in your machine

Script working in ipython but not from the command line

I have a script that functions from within ipython but when I try and run the same script from the command line I receive import errors for a local module that I am trying to import:
from helper_functions.email_from_server import send_email
Error:
ImportError: No module named helper_functions.email_from_server
This script imports from within Ipython without any issues.
Comparatively, I have code that runs without any issues within ipython I can run another script using the command:
run script.py
From the command line I can run the same script:
python /dir/script.py
However this python /dir/script.py doesn't work with the script with local imports (from above) and I can't figure out if its a pythonpath issue or some local env issue? I have been reading through stack to find it but haven't been able to thus far. It feels like its just around the corner
One attempted solution:
PYTHONPATH=/dir/ python /dir/script.py
EDIT (to help clarify):
I am using an anaconda distribution on a linux machine.
Mucking about with PYTHONPATH is a recipe for sadness. You can do it, but you shouldn't. The correct thing to do is install your package in your correct environment. If you don't know how to create a package here's a super simple example. There may be some differences in your path when running via ipython vs command line.
You can find out what the differences are by using sys.executable and sys.path:
import sys
print(sys.executable)
print(sys.path)
Run that from IPython, and then run that from the python on your command line. You will undoubtedly get two different results. Since you're running Anaconda, you want to follow their guide for installing non-conda packages to install the one that you build.
Though of course that assumes that you've got the anaconda python on your path - you can check that out with which python since you're on Linux.
I resolved it via creating a wrapper shell script. Ugly in that i'm exporting the python path each time, but it works.
#!/bin/bash
export PYTHONPATH="${PYTHONPATH}:/my/dir"
source ~/.bash_profile
cd /my/dir && my/anaconda/location/bin/python /my/dir/to/script/cript.py

How do I get linux to automatically run my python script in the Python interpreter?

I've decided that it would be good for me to move outside of my .NET bubble and start experimenting with other technologies. I have Ubuntu12 running and python2.7 and 3.2 are installed. I can run code directly in the interpreters.
I have a basic script on the filesystem called Standalone.py:
#!/usr/bin/env python3.2
import sys
print("this is a standalone script.")
When I'm at my bash prompt I type $ python3.2 Standalone.py. I get a response saying this is a standalone script. But when I type $ Standalone.py then it tells me that the command is not found.
How do I run such scripts?
Thanks for any help.
update
I changed the permissions of Standalone.py to 755. Then I ran the command:
$ ./Standalone.py
and received the message:
: No such file or directory
I then switched the permissions of Standalone.py back to 644. Then when I ran
$ ./Standalone.py
I received the message
-bash: ./Standalone.py: Permission denied
Is there something I'm missing?
You need to make the script executable using
chmod +x Standalone.py
Usually, the current directory is not searched for executable files, so you need to use
./Standalone.py
to tell the shell that the script is in the current directory.
Make sure your script file has linux newline (just \n) not windows newline (\r\n). Did you write the script on windows? This happened to me once. You should check your editor settings.
Your script should start with #!/usr/bin/python not #!/usr/bin/env python3.2
Make sure you're in the folder where your script is located you can check with ls
chmod +x Standalone.py
./Standalone.py
At first, to excecute a script it need to be executable. So you either have to do a chmod +x $file or a chmod 0740 $file. When you set the file permission to 644 you are putting the execute right away, so if gives you an error. If you are unsure of execution right and octal notation, you can use this : http://permissions-calculator.org/decode/0644/.
To really answer your question then, if you want to call the script with $file.py it needs to be in your PATH variable. You can display it with echo $PATH. Those are the directories that are searched for script to execute. So you simply need to give your script the executable right and put it in one of the directory given by your PATH.
Can you check if /usr/bin/python or /usr/bin/python3.2 exists
Execute below comamnd:
which python3.2
and then use the resulting path on top of you script.

Categories