Calling PARI/GP from Python

2024/9/8 9:07:25

I would like to call PARI/GP from Python only to calculate the function nextprime(n) for different ns that I define. Unfortunately I can't get pari-python to install so I thought I would just call it using a command line via os.system in Python. I can't see in the man page how to do get PARI/GP to run in non-interactive mode, however. Is there a way to achieve this?

Answer

You can pipe input into gp's stdin like so, using the -q flag to quash verbosity:

senderle:~ $ echo "print(isprime(5))" | gp -q
1

However, it's not much harder to create a simple python extension that allows you to pass strings to pari's internal parser and get results back (as strings). Here's a bare-bones version that I wrote some time ago so that I could call pari's implementation of the APRT test from python. You could extend this further to do appropriate conversions and so on.

//pariparse.c#include<Python.h>
#include<pari/pari.h>static PyObject * pariparse_run(PyObject *self, PyObject *args) {pari_init(40000000, 2);const char *pari_code;char *outstr;if (!PyArg_ParseTuple(args, "s", &pari_code)) { return NULL; }outstr = GENtostr(gp_read_str(pari_code));pari_close();return Py_BuildValue("s", outstr);
}static PyMethodDef PariparseMethods[] = {{"run", pariparse_run, METH_VARARGS, "Run a pari command."},{NULL, NULL, 0, NULL}
};PyMODINIT_FUNC initpariparse(void) {(void) Py_InitModule("pariparse", PariparseMethods);
}

And the setup file:

#setup.pyfrom distutils.core import setup, Extensionmodule1 = Extension('pariparse',include_dirs = ['/usr/include', '/usr/local/include'],libraries = ['pari'],library_dirs = ['/usr/lib', '/usr/local/lib'],sources = ['pariparse.c'])setup (name = 'pariparse',version = '0.01a',description = 'A super tiny python-pari interface',ext_modules = [module1])

Then just type python setup.py build to build the extension. You can then call it like this:

>>> pariparse.run('nextprime(5280)')
'5281'

I tested this just now and it compiled for me with the latest version of pari available via homebrew (on OS X). YMMV!

https://en.xdnf.cn/q/72619.html

Related Q&A

Can anyone explain why this sorting wont work?

For example if I have a list like this:List1 =[7,6,9] List1 = List1.sort()

Using argparse for mandatory argument without prefix

Im trying to use argparse module within my python application. My application should be run with single mandatory argument without any prefixes. I could not come up with a way to do it.

prevent unexpected stdin reads and lock in subprocess

A simple case Im trying to solve for all situations. I am running a subprocess for performing a certain task, and I dont expect it to ask for stdin, but in rare cases that I might not even expect, it m…

Regex split string by last occurrence of pattern

I am using regex to split a string <book name> by <author name> into book and author names.re.split(r\bby\b, text, 0, re.I)But problem arises when the book name contains the word "by&q…

How to write a unit-test where each test case has different input but does the same?

I need to create a unit-test for some python class. I have a database of inputs and expected results which should be generated by the UUT for those inputs.Here is the pseudo-code of what I want to do:f…

Unable to pass authentication information to NetSuites REST interface using Python

Ive been trying to get a NetSuite Restlet to work with Python 3.3 using urllib, but I cant seem to get the authorization to take and continually return a urllib.error.HTTPError: HTTP Error 401: Authori…

letsencrypt failed with ImportError: No module named interface

Im using Amazon linux, and I followed some steps for using letsencrypt that easily found in google search, but all it fails with:Error: couldnt get currently installed version for /root/.local/share/le…

ModuleNotFoundError: No module named skimage.util.montage

Im trying to import montage2d module from scikit-image:from skimage.util.montage import montage2dBut this error popped up:ModuleNotFoundError: No module named skimage.util.montageIm pretty sure I insta…

upgrading python module within code

My question relates to this question: Installing python module within code, but involves upgrading the module.Ive triedpackages=[apscheduler,beautifulsoup4,gdata]def upgrade(packages):for package in pa…

Django - 403 Forbidden CSRF verification failed

I have a contact form in Django for my website and when I was testing it locally it was working fine but now when I try to submit my contact form "live" it always comes up with 403 Forbidden …