Ask Your Question

How to write a standalone cython script?

asked 2019-04-11 18:10:44 +0200

ablmf gravatar image

updated 2019-04-12 04:32:06 +0200

slelievre gravatar image

To use Cython in sage, according to the document, you can either write Cython code in a sage notebook, load a .spyx file from command line, or create a .pyx file and add it to the sage library.

My question is, can we write a standalone cython script and run it with sage? Just like a normal sage standalone script.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2019-04-12 06:05:44 +0200

nbruin gravatar image

The problem is: there is no such thing as a "cython script". Cython builds python extension modules, which can contain code that runs when the extension module is loaded (with "import").

There is the sage command "cython", however, which builds the module and immediately loads it, and imports its bindings into the toplevel namespace. That makes it seem you can use scripts.

A "standalone" script could be written using something like

#!/usr/local/bin/sage --python
from sage.all import *
from sage.repl.user_globals import set_globals
def cyprint(s):
cyprint("Hello world")

If you put that in a file and mark it executable, you should be able to execute the script by typing in its name (together with a path, depending on your configuration). You can't do this directly with a "sage" script since it would want to preparse things. The "set_globals" thing is a peculiarity that the "cython" command needs. It may be possible to streamline this use further.

Of course this is a very inefficient way to go about things: you'll be recompiling this module every time you invoke the script. For any serious work you should just build a cython module and make sure it's in a place where you can import that module in the script in which you want to use it.

edit flag offensive delete link more


Actually, I found that you can write a Cython program with .spyx extension and run it with sage. sage will compile it first and then run the compiled program. This is not efficient if we have to run the script many times. But it is fine for me since I am running a very long simulation and the compilation time of the program is negligible.

ablmf gravatar imageablmf ( 2019-04-12 09:41:59 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2019-04-11 18:10:44 +0200

Seen: 465 times

Last updated: Apr 12 '19