Home > OS >  How to run a cython script through a python file?
How to run a cython script through a python file?

Time:08-31

I have a compiled cython script which i normally run in powershell by typing py and then import main. But Is there a way to run the script in a python file so i can just run python run.py in powershell?

I tried using subprocess but it didn't work and i couldn't figure it out.

import subprocess

subprocess.system('py')
subprocess.system('import main')

CodePudding user response:

You make a run.py file or whatever you want to call it. Then add import main to the file. Then you run it by typing python run.py.
You should just be able to import it like any other python module, just make sure the files are located in the same directory. (or look at Importing files from different folder)

To verify with fib.pyx example from cython tutorial.
first we make the fib.pyx file containing the code below.

from __future__ import print_function

def fib(n):
    """Print the Fibonacci series up to n."""
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a   b

    print()

To verify we cant already use it by making a small test.py file.

import fib 
fib.fib(2000)

running that with python test.py will give the errorModuleNotFoundError: No module named 'fib'.

So we continue to make a setup.py file

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize("fib.pyx"),
)

Now running python setup.py build_ext --inplace will build your extension. Now if you run python test.py again it will not give an error and it will output. 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 What is the same but now for a file as they did in the tutorial by launching the python interpreter and running

>>> import fib
>>> fib.fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

(I also tested this on the pure cython function primes and it works the same, you can just run it from a file if you write it exactly like you would in the interpeter and just run it using python <fileName>.py)

  • Related