import fortran object into Python - python

I'm trying to compile some project I've found on the web.
the project is wrapping some Fortran code into python object.
The author of that project wrote I need to run the setup.py file.
I've done that. It contains the following piece of code:
ext = Extension(name = "GaussianFitter._Fitter",
sources = ["GaussianFitter/src/lmdif.f",
"GaussianFitter/src/splev.f",
"GaussianFitter/src/gaussian.f90"],
and obviously all these "f" files are existing.
When I install that setup.py file it seams to do some job succesfully but the first line in the script which uses that _Fitter:
import _Fitter
doesn't work.
I'm newby with python, and have no experiment with Fortran at all, so please forgive my ignorance.
Edit: project available here:
https://github.com/ardiloot/GaussianFitter
Thanks!

Finally made it, so here's my for-begginers tutorial:
note - since it's for beginners - it sets all in the global scope.
install mingw32 from:
http://www.mingw.org/
Add it's bin path to system PATH.
add a setup.cfg file containing the following text:
[build]
compiler=mingw32
locate it in %pythondir%\Lib\distutils
since setup.py file contains links to .c or .f files (c++/fortran/c) in order to make command (python setup.py install) be able to locate these files - run the command when working directory (i.e. cd c:....\) is set.
Ignore red error line in code when you import that module. It is in the LIB directory, just try to run...
EDIT:
If still not managing to import the already built f files - building it in the following way might help:
python setup.py build_ext --inplace
which generates an object (*.pyd), this helped me after it, for any reason, stopped working.

Related

Cant import local module

So I am trying to use this repository on my computer but I cant seem to import a local module (Agent.pyx) and use functions from that file. The error I get is:
ModuleNotFoundError: No module named 'RLAgent.Agent
Screenshot of error
Link to repository
You have to install the package manually
Since Agent.pyx is a .pyx file, you will need to first build it. The README file in the linked repo also mentions this. So you need to move to the RLAgent directory and execute the setup instruction as:
cd RLAgent
python3 setup.py build_ext --inplace
This will build the required .c and .so file which will then enable it's import in other files such as Train.py which is where the import is throwing an error.

How to download executable(ANTLRv4) to generate files during pip install

The library I'm working on generates python files according to an executable (which turns ANTLRv4 .g4 files into python files), and I have the following install step:
import os
import subprocess
from setuptools import setup
from setuptools.command.install import install
class AntlrInstallCommand(install):
def run(self):
output_dir = compile_grammar()
print(f"Compiled ANTLRv4 grammar in {output_dir}")
install.run(self)
def compile_grammar():
parser_dir = os.path.join(os.path.dirname(__file__), "my_project/grammar")
subprocess.check_output(
["antlr", "MyGrammar.g4", "-Dlanguage=Python3", "-visitor", "-o", "gen"],
cwd=parser_dir,
)
# The result is created in the subfolder `gen`
return os.path.join(parser_dir, "gen")
setup(
...
install_requires=[
"setuptools",
"antlr4-python3-runtime==4.9.2",
...
],
cmdclass={"install": AntlrInstallCommand},
license="MIT",
python_requires=">=3.6",
)
Which works great if I'm pip install'ing the project on a machine that has antlr installed (since I'm calling it via subprocess).
Ideally, attempting to do this on a machine that doesn't have antlr installed would first install the executable(with the correct version) in either a system directory like /usr/bin, or whatever relevant python bin directory we're working in, but right now it errors out with the following message(which is expected):
running install
error: [Errno 2] No such file or directory: 'antlr'
----------------------------------------
ERROR: Failed building wheel for my_project
I see a couple of solutions each with slight caveats:
sympy uses ANTLR, but it requires the user to install antlr first. See here
setuptools-antlr allows me to download an antlr jar as a giant blob in a python package, and then I can invoke it here. However, the version doesn't match mine (which is 4.9.2).
java2python precompiles the files for me and writes them into the github repo. However, these files are extremely large and are very hard to read as they're autogenerated. If I slightly modify the grammar and don't modify the parser it would also lead to unexpected bugs. As a result, I would like to hide this complexity from the repository as it's tangential to development.
If I can get the right version of the antlr binary and be able to invoke it at install time, that would be optimal. Otherwise I'm okay with picking one of these alternatives. Any suggestions for either case would be appreciated.

Building Python-C Extension using CFFI, but Setuptools does not include custom header files in build

I'm trying to use the CFFI package in Python to create a Python interface for already existing C-code.
I am able to compile a C library by following this blog post. Now I want to make it so that this python library is available without any fancy updates to the sys.path.
I found that maybe creating a distribution through Python's setuptools setup() function would accomplish this and I got it to mostly work by creating a setup.py file as such
import os
import sys
from setuptools import setup, find_packages
os.chdir(os.path.dirname(sys.argv[0]) or ".")
setup(
name="SobelFilterTest",
version="0.1",
description="An example project using Python's CFFI",
packages=find_packages(),
install_requires=["cffi>=1.0.0"],
setup_requires=["cffi>=1.0.0"],
cffi_modules=[
"./src/build_sobel.py:ffi",
"./src/build_file_operations.py:ffi",
],
)
, but I run into this error
build/temp.linux-x86_64-3.5/_sobel.c:492:19: fatal error: sobel.h: No such file or directory
From what I can tell, the problem is that the sobel.h file does not get uploaded into the build folder created by setuptools.setup(). I looked for suggestions of what to do including using Extensions() and writing a MANIFEST.in file, and both seem to add a relative path to the correct header files:
MANIFEST.in
setup.py
SobelFilterTest.egg-info/PKG-INFO
SobelFilterTest.egg-info/SOURCES.txt
SobelFilterTest.egg-info/dependency_links.txt
SobelFilterTest.egg-info/requires.txt
SobelFilterTest.egg-info/top_level.txt
src/file_operations.h
src/macros.h
src/sobel.h
But I still get the same error message. Is there a correct way to go about adding the header file to the build folder? Thanks!
It's actually not pip that is missing the .h file, but rather the compiler (like gcc). Therefore it's not about adding the missing file to setup, but rather make sure that cffi can find it. One way (like mentioned in the comments) is to make it available to the compiler through environment variables, but there is another way.
When setting the source with cffi you can add directories for the compiler like this:
from cffi import FFI
ffibuilder = FFI()
ffibuilder.set_source("<YOUR SOURCE HERE>", include_dirs=["./src"])
# ... Rest of your code
"""

py2exe can't find .py

Sorry if this is a really stupid question,
How do I get the py2exe to find the module I wish to convert?
I keep getting this error:
C:\Python27\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'dist_dir'
warnings.warn(msg)
running py2exe
creating C:\Users\David\workspace\setup\src\dist
*** searching for required modules ***
error: Pygame.py: No such file or directory
I looked up as many Pygame to .exe tutorials or problems others have had, but their problem seemed to occur AFTER they created a .exe file...
I can't even get it to create one.
I used the exact same code as the one found on http://pygame.org/wiki/Pygame2exe except that I changed:
class BuildeExe:
def __init__(self):
#Name of starting .py
self.script = "MyApps.py"
into
class BuildExe:
def __init__(self):
#Name of starting .py
self.script = "Pygame.py"
My Pygame.py exists in "C:\Users\"username"\workspace\pygame\src". Please help.
you can try putting this in a .py file:
from distutils.core import setup
import py2exe
setup(console=['hello.py'])
such as how they do in this tutorial. Then all you have to do is oppen up cmd.exe and cd to your "C:\Users\"username"\workspace\pygame\src" and type:
python setup.py py2exe
or you can changed the setup.py to whatever .py file you saved the above code in. (within the same directory as you gave)

How to build a distribution file?

I have created the setup.py file. But I don't know how to make a distribution?
The book said that Open a terminal window and type a single command: python3 setup.py sdist. I did that but always get error!
I feel the code is ok, because it is just the example in the book. I guess the error is from the way I build the distribution.
In the python command line terminal, how to change directory?
The code of file nester.py goes like following:
def print_lol(the_list):
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item)
else:
print(each_item)
The setup.py file is as following:
from distutils.core import setup
setup(
name = 'nester',
version = '1.0.0',
py_modules = ['nester'],
author = 'hfpython',
author_email = 'hfpython#headfirstlabs.com',
url = 'http://www.headfirstlabs.com',
description = 'A simple printer of nested lists',
)
And the command I type in is: python3 setup.py sdist then I get the error:
File "<stdin>",line 1
pythons setup.py sdist
syntaxError: invalid syntax
In the python command line terminal, how to change directory?
Irrelevant, since this isn't supposed to be entered into the Python REPL. Enter it into the shell/command prompt instead.
Make sure you add the path if Python is not installed in your c drive, and add the Python file name correctly (the python file is named automatically according to its version while installed). Also make sure the setup.py file is inside the Python file.
For example, I installed my python in e drive and the version is 3.4.2. The file name created automatically for it is Python34.
in the command line, I typed:
e:\Python34\setup.py sdist
Hope this help.
Joey
Since you are on windows, so depending upon the python version & install location of python
use command as like.
First you must be clear of the path to python.
C:\python33\python setup.py sdist
I hope this helps.

Categories

Resources