0

The python print() will only print its arguments like a tuple after this .py is CPython-compiled into a .so and being imported. How can it behave like it is a normal py file?

The scenarios is like this. Here is a function output() defined in mod4.py:

def output(a, b):
    print(a, b, str(a)+str(b))

I use following main.py to call output():

import mod4
mod4.output(2, 3)

the output will be like:

2 3 23

Then I compile mod4.py using CPython, by editing a setup.py like:

from distutils.core import setup
from Cython.Build import cythonize

setup(name="mod4.app", ext_modules=cythonize("mod4.py"))

and execute python setup.up build_ext --inplace in command line, which in turn generates mod4.cpython-37m-darwin.so. Then main.py will output like:

(2, 3, '23')

it looks just like a tuple of the arguments of print().

The version of python is 3.7.4,

$ python --version
Python 3.7.4

How can I get output() in .so outputs just like it in .py?

Cuteufo
  • 501
  • 6
  • 15
  • I would guess that the compiled version is based on python2. – quamrana Dec 01 '19 at 09:56
  • I am using python 3.7.4 generally in my own environment. How to tell specifically what version is used by the compiled version? – Cuteufo Dec 01 '19 at 10:19
  • Well, what is the command line which produces your .so? Surely a —version option will tell you. – quamrana Dec 01 '19 at 14:27
  • I edited OP with details of compiling the .so and python version. thanks! – Cuteufo Dec 01 '19 at 19:39
  • You need to provide language level 3 to cythonize, otherwise python2 syntax is assumed. When you compile the must be a warning telling you that – ead Dec 02 '19 at 09:59

1 Answers1

0

thanks for your advice, @quamrana and @ead. With your hints and a reference to How to specify Python 3 source in Cython's setup.py?, I edited the setup.py like following (added language_level="3" in cythonize() call):

from distutils.core import setup
from Cython.Build import cythonize

setup(name="mod4.app", ext_modules=cythonize("mod4.py", language_level="3"))

and the output becomes what I expect.

Cuteufo
  • 501
  • 6
  • 15