I'm using PythonKit in my Swift project for MacOS. At the moment I'm using Python 2.7 but from MacOs 12.3 it isn't no more supported so I'm trying to migrate to Python 3 but it doesn't work.
func applicationDidFinishLaunching(_ notification: Notification) {
if #available(OSX 12, *) {
PythonLibrary.useVersion(3)
}
else {
PythonLibrary.useVersion(2)
}
let sys = Python.import("sys")
print("Python \(sys.version_info.major).\(sys.version_info.minor)")
print("Python Version: \(sys.version)")
print("Python Encoding: \(sys.getdefaultencoding().upper())")
sys.path.append(Bundle.main.resourceURL!.absoluteURL.path)
let checker = Python.import("checkLibrary")
_ = Array(checker.check())
}
This is the error message:
PythonKit/PythonLibrary.swift:46: Fatal error: Python library not found. Set the PYTHON_LIBRARY environment variable with the path to a Python library.
The code fail on MacOs 12 on line 9th line (let sys = Python.import("sys")), so I can't interact so sys in any way.
I've already tried to disable sandbox and Hardened Runtime but is seems useless.
I was having the same issue.
where python3
which python3
type -a python3
I could clearly see that Python3 was present using any of the above commands from terminal. Python3 wasnt something that I directly installed, (probably something I added during an install of XCode) but I could see it located at "/usr/bin/python3"
I had already removed the sandbox and disabled the hardened runtime.
Adding the environment variable to XCode did not work and Google ultimately told me to do what had already been done.
Finally, I decided to just perform a fresh install, following the blog as guidance.
https://www.dataquest.io/blog/installing-python-on-mac/#installing-python-mac
https://www.python.org/downloads/macos/ (direct URL for Python download)
After installing, everything worked as expected.
PythonLibrary.useVersion(3)
PythonLibrary.useLibrary(at: "/usr/local/bin/python3")
I could use either of the above methods, without adding the environment variable to the XCode scheme.
Hopefully that helps
Related
I have two python environments with different versions running in parallel. When I execute a python script (test2.py) from one python environment in the other python environment, I get the following error:
Fatal Python error: Py_Initialize: can't initialize sys standard streams
Traceback (most recent call last):
File "C:\ProgramData\Miniconda3\envs\GMS_VENV_PYTHON\lib\io.py", line 52, in <module>
File "C:\ProgramData\Miniconda3\envs\GMS_VENV_PYTHON\lib\abc.py", line 147
print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file)
^
SyntaxError: invalid syntax
So my setup is this:
Python 3.7
(test.py)
│
│ Python 3.5.6
├───────────────────────────────┐
┆ │
┆ execute test2.py
┆ │
┆ 🗲 Error
How can I fix this?
For dm-script-people: How can I execute a module with a different python version in Digital Micrograph?
Details
I have two python files.
File 1 (test.py):
# execute in Digital Micrograph
import os
import subprocess
command = ['C:\\ProgramData\\Miniconda3\\envs\\legacy\\python.exe',
os.path.join(os.getcwd(), 'test2.py')]
print(*command)
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print("Subprocess result: '{}', '{}'".format(result.stdout.decode("utf-8"), result.stderr.decode("utf-8")))
and File 2 (test2.py)
# only executable in python 3.5.6
print("Hi")
in the same directory. test.py is executing test2.py with a different python version (python 3.5.6, legacy environment).
My python script (test.py) is running in the python interpreter in a third party program (Digital Micrograph). This program installs a miniconda python enviromnent called GMS_VENV_PYTHON (python version 3.7.x) which can be seen in the above traceback. The legacy miniconda environment is used only for running test2.py (from test.py) in python version 3.5.6.
When I run test.py from the command line (also in the conda GMS_VENV_PYTHON environment), I get the expected output from test2.py in test.py. When I run the exact same file in Digital Micrograph, I get the response
Subprocess result: '', 'Fatal Python error: Py_Initialize: can't initialize sys standard streams
Traceback (most recent call last):
File "C:\ProgramData\Miniconda3\envs\GMS_VENV_PYTHON\lib\io.py", line 52, in <module>
File "C:\ProgramData\Miniconda3\envs\GMS_VENV_PYTHON\lib\abc.py", line 147
print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file)
^
SyntaxError: invalid syntax
'
This tells me the following (I guess):
The test2.py is called since this is the error output of the subprocess call. So the subprocess.run() function seems to work fine
The paths are in the GMS_VENV_PYTHON environment which is wrong in this case. Since this is test2.py, they should be in the legacy paths
There is a SyntaxError because a f-string (Literal String Interpolation) is used which is introduced with python 3.6. So the executing python version is before 3.6. So the legacy python environment is used.
test2.py uses either use io nor abc (I don't know what to conclude here; are those modules loaded by default when executing python?)
So I guess this means, that the standard modules are loaded (I don't know why, probably because they are always loaded) from the wrong destination.
How can I fix this? (See What I've tried > PATH for more details)
What I've tried so far
Encoding
I came across this post "Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: 65001" telling me, that there might be problems with the encoding. I know that Digital Micrograph internally uses ISO 8859-1. I tried to use python -X utf8 and python -X utf8 (test2.py doesn't care about UTF-8, it is ASCII only) as shown below. But neither of them worked
command = ['C:\\ProgramData\\Miniconda3\\envs\\legacy\\python.exe',
"-X", "utf8=0",
os.path.join(os.getcwd(), 'test2.py')]
PATH
As far as I can tell, I think this is the problem. The answer "https://stackoverflow.com/a/31877629/5934316" of the post "PyCharm: Py_Initialize: can't initialize sys standard streams" suggests to change the PYTHONPATH.
So to specify my question:
Is this the way to go?
How can I set the PYTHONPATH for only the subprocess (while executing python with other libraries in the main thread)?
Is there a better way to have two different python versions at the same time?
Thank you for your help.
Background
I am currently writing a program for handling an electron microscope. I need the "environment" (the graphical interface, the help tools but also hardware access) from Digital Micrograph. So there is no way around using it. And DigitalMicrograph does only support python 3.7.
On the other hand I need an external module which is only available for python 3.5.6. Also there is no way around using this module since it controlls other hardware.
Both rely on python C modules. Since they are compiled already, there is no possibility to check if they work with other versions. Also they are controlling highly sensitive aperatures where one does not want to change code. So in short words: I need two python versions parallel.
I was actually quite close. The problem is, that python imports invalid modules from a wrong location. In my case modules were imported from another python installation due to a wrong path. Modifying the PYTHONPATH according to "https://stackoverflow.com/a/4453495/5934316" works for my example.
import os
my_env = os.environ.copy()
my_env["PYTHONHOME"] = "C:\\ProgramData\\Miniconda3\\envs\\legacy"
my_env["PYTHONPATH"] = "C:\\ProgramData\\Miniconda3\\envs\\legacy;"
my_env["PATH"] = my_env["PATH"].replace("C:\\ProgramData\\Miniconda3\\envs\\GMS_VENV_PYTHON",
"C:\\ProgramData\\Miniconda3\\envs\\legacy")
command = ["C:\\ProgramData\\Miniconda3\\envs\\legacy\\python.exe",
os.path.join(path, "test2.py")]
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env)
For Digital Micrograph users: The python environment is saved in the global tags in "Private:Python:Python Path". So replace:
import DigitalMicrograph as DM
# ...
success, gms_venv = DM.GetPersistentTagGroup().GetTagAsString("Private:Python:Python Path")
if not success:
raise KeyError("Python path is not set.")
my_env["PATH"] = my_env["PATH"].replace(gms_venv, "C:\\ProgramData\\Miniconda3\\envs\\legacy")
I had set "PYTHONPATH" as "D:\ProgramData\Anaconda3" for my python (base) python environment before, but i found when I had changed to another env my python still import basic python package from "D:\ProgramData\Anaconda3",which means it get the wrong basic package with the wrong "System environment variables" config.
so I delete "PYTHONPATH" from my windows "System environment variables", and that will be fixed.
I'm new to working with azure functions and tried to work out a small example locally, using VS Code with the Azure Functions extension.
Example:
# First party libraries
import logging
# Third party libraries
import numpy as np
from azure.functions import HttpResponse, HttpRequest
def main(req: HttpRequest) -> HttpResponse:
seed = req.params.get('seed')
if not seed:
try:
body = req.get_json()
except ValueError:
pass
else:
seed = body.get('seed')
if seed:
np.random.seed(seed=int(seed))
r_int = np.random.randint(0, 100)
logging.info(r_int)
return HttpResponse(
"Random Number: " f"{str(r_int)}", status_code=200
)
else:
return HttpResponse(
"Insert seed to generate a number",
status_code=200
)
When numpy is installed globally this code works fine. If I install it only in the virtual environment, however, I get the following error:
*Worker failed to function id 1739ddcd-d6ad-421d-9470-327681ca1e69.
[15-Jul-20 1:31:39 PM] Result: Failure
Exception: ModuleNotFoundError: No module named 'numpy'. Troubleshooting Guide: https://aka.ms/functions-modulenotfound*
I checked multiple times that numpy is installed in the virtual environment, and the environment is also specified in the .vscode/settings.json file.
pip freeze of the virtualenv "worker_venv":
$ pip freeze
azure-functions==1.3.0
flake8==3.8.3
importlib-metadata==1.7.0
mccabe==0.6.1
numpy==1.19.0
pycodestyle==2.6.0
pyflakes==2.2.0
zipp==3.1.0
.vscode/settings.json file:
{
"azureFunctions.deploySubpath": ".",
"azureFunctions.scmDoBuildDuringDeployment": true,
"azureFunctions.pythonVenv": "worker_venv",
"azureFunctions.projectLanguage": "Python",
"azureFunctions.projectRuntime": "~2",
"debug.internalConsoleOptions": "neverOpen"
}
I tried to find something in the documentation, but found nothing specific regarding the virtual environment. I don't know if I'm missing something?
EDIT: I'm on a Windows 10 machine btw
EDIT: I included the folder structure of my project in the image below
EDIT: Added the content of the virtual environment Lib folder in the image below
EDIT: Added a screenshot of the terminal using the pip install numpy command below
EDIT: Created a new project with a new virtual env and reinstalled numpy, screenshot below, problem still persists.
EDIT: Added the launch.json code below
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to Python Functions",
"type": "python",
"request": "attach",
"port": 9091,
"preLaunchTask": "func: host start"
}
]
}
SOLVED
So the problem was neither with python, nor with VS Code. The problem was that the execution policy on my machine (new laptop) was set to restricted and therefore the .venv\Scripts\Activate.ps1 script could not be run.
To resolve this problem, just open powershell with admin rights and and run set-executionpolicy remotesigned. Restart VS Code and all should work fine
I didn't saw the error, due to the many logging in the terminal that happens
when you start azure. I'll mark the answer of #HuryShen as correct, because the comments got me to the solution. Thank all of you guys
For this problem, I'm not clear if you met the error when run it locally or on azure cloud. So provide both suggestions for these two situation.
1. If the error shows when you run the function on azure, you may not have installed the modules success. When deploy the function from local to azure, you need to add the module to requirements.txt(as Anatoli mentioned in comment). You can generate the requirements.txt automatically by the command below:
pip freeze > requirements.txt
After that, we can find the numpy==1.19.0 exist in requirements.txt.
Now, deploy the function from local to azure by the command below, it will install the modules success on azure and work fine on azure.
func azure functionapp publish <your function app name> --build remote
2. If the error shows when you run the function locally. Since you provided the modules installed in worker_venv, it seems you have installed numpy module success. I also test it in my side locally, install numpy and it works fine. So I think you can check if your virtual environment(worker_venv) exist in the correct location. Below is my function structure in local VS code, please check if your virtual environment locates in the same location with mine.
-----Update------
Run the command to to set execution policy and then activate the virtual environment:
set-executionpolicy remotesigned
.venv\Scripts\Activate.ps1
I could solve my issue uninstalling python3 (see here for a guide https://stackoverflow.com/a/60318668/11986067).
After starting the app functions via F5 or func start, the following output was shown:
This version was incorrect. I have chosen python 3.7.0 when creating the project in the Azure extension. After deleting this python3 version, the correct version was shown and the Import issue was solved:
I want to compile my python code to binary by using pyinstaller, but the hidden import block me. For example, the following code import psutil and print the CPU count:
# example.py
import psutil
print psutil.cpu_count()
And I compile the code:
$ pyinstaller -F example.py --hidden-import=psutil
When I run the output under dist:
ImportError: cannot import name _psutil_linux
Then I tried:
$ pyinstaller -F example.py --hidden-import=_psutil_linux
Still the same error. I have read the pyinstall manual, but I still don't know how to use the hidden import. Is there a detailed example for this? Or at least a example to compile and run my example.py?
ENVs:
OS: Ubuntu 14.04
Python: 2.7.6
pyinstaller: 2.1
Hi hope you're still looking for an answer. Here is how I solved it:
add a file called hook-psutil.py
from PyInstaller.hooks.hookutils import (collect_data_files, collect_submodules)
datas = [('./venv/lib/python2.7/site-packages/psutil/_psutil_linux.so', 'psutil'),
('./venv/lib/python2.7/site-packages/psutil/_psutil_posix.so', 'psutil')]
hiddenimports = collect_submodules('psutil')
And then call pyinstaller --additional-hooks-dir=(the dir contain the above script) script.py
pyinstall is hard to configure, the cx_freeze maybe better, both support windows (you can download the exe directly) and linux. Provide the example.py, In windows, suppose you have install python in the default path (C:\\Python27):
$ python c:\\Python27\\Scripts\\cxfreeze example.py -s --target-dir some_path
the cxfreeze is a python script, you should run it with python, then the build files are under some_path (with a lot of xxx.pyd and xxx.dll).
In Linux, just run:
$ cxfreeze example.py -s --target-dir some_path
and also output a lot of files(xxx.so) under some_path.
The defect of cx_freeze is it would not wrap all libraries to target dir, this means you have to test your build under different environments. If any library missing, just copy them to target dir. A exception case is, for example, if your build your python under Centos 6, but when running under Centos 7, the missing of libc.so.6 will throw, you should compile your python both under Centos 7 and Centos 6.
What worked for me is as follows:
Install python-psutil: sudo apt-get install python-psutil. If you
have a previous installation of the psutil module from other
method, for example through source or easy_install, remove it first.
Run pyinstaller as you do, without the hidden-import option.
still facing the error
Implementation:
1.python program with modules like platform , os , shutil and psutil
when i run the script directly using python its working fine.
2.if i build a binary using pyinstaller. The binary is build successfully. But if i run the binary iam getting the No module named psutil found.I had tried several methods like adding the hidden import and other things. None is working. I trying it almost 2 to 3 days.
Error:
ModuleNotFoundError: No module named 'psutil'
Command used for the creating binary
pyinstaller --hidden-import=['_psutil_linux'] --onefile --clean serverHW.py
i tried --additional-hooks-dir= also not working. When i run the binary im getting module not found error.
I run Python Scripts on our Dreamhost Server. Our Python scripts use Python 2.7 - we made a custom installation because Dreamhost uses Python 2.6. Everything worked fine for 1 year.
Dreamhost did a server update yesturday and now our scripts fail to find a specific module - MD5. The scripts output the error below when we go to import hashlib.
What do I need to do to rectify this?
Should I reinstall Python 2.7?
Should I reinstall Pip and Easy_Install?
Should I reinstall VirtualEnv?
Is there something else you recommend I do?
Error from all Python scripts:
/home/user/script.py in ()
import hashlib
hashlib undefined
/home/user/python/lib/python2.7/hashlib.py in ()
# version not supporting that algorithm.
try:
globals()[__func_name] = __get_hash(__func_name)
except ValueError:
import logging builtin globals = <built-in function globals, __func_name = 'md5', __get_hash = <function __get_builtin_constructor /home/user/python/lib/python2.7/hashlib.py in __get_builtin_constructor(name='md5')
return _sha.new
elif name in ('MD5', 'md5'):
import _md5
return _md5.new
elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
_md5 undefined
<type 'exceptions.ImportError': No module named _md5
args = ('No module named _md5',)
message = 'No module named _md5'
I was having the exact same issue. I run Python 2.7 in my own virtualenv.
I am trying to avoid reinstalling python and run a Django 1.7 application.
The following approach works for me.
STEP 1. (This step might not be necessary)
I uninstalled pythonbrew since it says here: http://wiki.dreamhost.com/Python
that pythonbrew has been deprecated.
If you were doing this from scratch pyenv is way to go, but you don't need to reinstall
virtualenv, etc. Just get rid of pythonbrew to start with.
$ rm -Rf ~/.pythonbrew
Removed references in .bashrc to pythonbrew
STEP 2.
There is no need to re-install virtualenv. Just create a new virtual env
$~/env> virtualenv myNewEnvironment
$~/env/myNewEnvironment/bin> source activate
$ pip freeze
You have a clean slate now, start rebuilding dependencies from scratch.
At least is solves the "import hashlib" issue. This gives you a clean
version of python properly linked to the new Ubuntu OS.
(myNewEnvironment):~> which python
~/env/myNewEnvironment/bin/python
(myNewEnvironment):~> python
Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
installed on Ubuntu 12.04 (which is the new OS)
Verify:
import hashlib should not throw error
STEP 3.
pip install Django
pip install MySQL-python
Its also probably safer to complete/recheck the remaining steps listed out in
http://wiki.dreamhost.com/Django (or appropriate wiki page for your framework)
For now this allows me to get my site up and running, (but) there is a warning
that I am ignoring for now until I figure out more:
You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.
Good luck!
I am trying to embed python 2.6 in .NET 4.0.
Following the very minimal documentation in "Python for .NET", I wrote a fairly straightforward code as follows:
const string pythonModulePath = #"C:\Projects\PythonImport\PythonImport\test.py";
Environment.SetEnvironmentVariable("PYTHONHOME", Path.GetDirectoryName(python
ModulePath));
PythonEngine.Initialize();
var oldWorkingDirectory = Directory.GetCurrentDirectory();
var currWorkingDirectory = Path.GetDirectoryName(pythonModulePath);
Directory.SetCurrentDirectory(currWorkingDirectory);
var pyPlugin = PythonEngine.ImportModule(Path.GetFileNameWithoutExtension(python
ModulePath));
if (pyPlugin == null)
{
throw new PythonException();
}
Directory.SetCurrentDirectory(oldWorkingDirectory);
Even if test.py is empty I get an import error saying "No module named warnings".
'import site' failed; use -v for traceback
Unhandled Exception: Python.Runtime.PythonException: ImportError : No module nam
ed warnings
The reason becomes apparent when you run test.py using "python -v" (verbose mode). Notice that python calls #cleanup[2] warnings.
Why is Python .NET not able to resolve warnings? The module is present in Lib directory.
Any ideas?
I think by default the Python Engine does not set the paths you need automatically.
http://www.voidspace.org.uk/ironpython/custom_executable.shtml has an example for embedding ironpython. Looks like you are missing something like
PythonEngine engine = new PythonEngine();
engine.AddToPath(Path.GetDirectoryName(Application.ExecutablePath));
engine.AddToPath(MyPathToStdLib);
Unless I know where and if Ironpython is installed, I prefer to find all of the standard modules I need, compile them to a IPyStdLibDLL and then do th following from my code
import clr
clr.addReference("IPyStdLib")
import site
#SilentGhost I don't know if you figured this out, but you need to set your PYTHONPATH environment variable rather than your PYTHONHOME variable. I, too, had the problem, set the environment variable with the ol' Environment.SetVariable("PYTHONPATH", ...) and everything worked out well in the end.
Good luck with the Python.NET.
I'm working with the 2.4 version of Python.NET with Python 3.6 and I had similar issues. I didn't have much luck setting environment variables at runtime but I found the following approach worked.
I found Python.NET was picking up all packages in the folders defined in the static PythonEngine.PythonPath variable. If you have other directories set in the PYTHONPATH system variable, it will also include these too.
To include module directories at runtime you can do something like
PythonEngine.PythonPath = PythonEngine.PythonPath + ";" + moduleDirectory;
using (Py.GIL())
{
dynamic module = Py.Import("moduleName");
...etc
}
Make sure you set the PythonEngine.PythonPath variable before making any calls to the python engine.
Also needed to restart visual studio to see any system variable changes take effect when debugging.
As a side note, I also found that my \Python36\Lib\site-packages folder path needed to be added to PYTHONPATH to pick up anything installed through pip.