从Python调用PARI/GP [英] Calling PARI/GP from Python
问题描述
我只想从Python调用 PARI/GP 为我定义的不同 n
计算函数 nextprime(n)
.不幸的是,我无法安装 pari-python ,所以我以为我会打电话给通过Python中的 os.system
使用命令行.我在手册页中看不到如何使PARI/GP在非交互模式下运行.有没有办法做到这一点?
I would like to call PARI/GP from Python only to calculate the function nextprime(n)
for different n
s 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?
推荐答案
您可以使用 -q
标志将输入通过管道输入到gp的stdin中,以消除冗长:
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
然而,创建一个简单的 python 扩展并没有困难得多,它允许您将字符串传递给 pari 的内部解析器并返回结果(作为字符串).这是我前一段时间写的一个简单的版本,因此我可以从python调用pari的 APRT测试的实现.您可以进一步扩展它以进行适当的转换,等等.
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);
}
安装文件:
#setup.py
from distutils.core import setup, Extension
module1 = 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])
然后只需键入 python setup.py build
即可构建扩展.然后您可以这样称呼它:
Then just type python setup.py build
to build the extension. You can then call it like this:
>>> pariparse.run('nextprime(5280)')
'5281'
我刚刚对此进行了测试,并使用可通过自制程序(在OS X上)获得的最新版本的pari对其进行了编译.YMMV!
I tested this just now and it compiled for me with the latest version of pari available via homebrew (on OS X). YMMV!
这篇关于从Python调用PARI/GP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!