Commit 594c1d3b authored by Stefan Behnel's avatar Stefan Behnel

add script "bin/pcython" to run Cython with a Python-like command line interface

parent 9cc4da5a
#!/usr/bin/env python
Script to run Cython with a Python command line.
Executes Python code by compiling it in Cython and running the compiled code.
import sys
import subprocess
def parse_args(args=None):
import argparse
parser = argparse.ArgumentParser(description='Run a Python command line with Cython')
parser.add_argument('-c', metavar='CODE', dest='command',
help='program passed in as string')
parser.add_argument('--python', metavar='PYTHON', dest='python', default=sys.executable,
help='Python interpreter to use')
parser.add_argument('-X', metavar='NAME=VALUE', dest='directives', action='append',
help='Compiler directives to set during compilation')
parser.add_argument('-V', '--version', action='store_true',
help='print the Python and Cython version numbers and exit')
parser.add_argument('file_args', nargs='*',
help='program read from script file')
return parser.parse_args(args)
def run_python(python, command):
subprocess.check_call([python, '-c', command])
def print_versions(python):
"""Print version numbers of Python and Cython.
command = (
"import sys, Cython; "
"print('Python {}'.format('.'.join(map(str, sys.version_info[:3])))); "
"print('[Cython {}]'.format(Cython.__version__))"
run_python(python, command)
def run_cython_command(python, command, args=None):
"""Compile and run a Python command string.
command = (
"import sys; "
"from Cython.Build.Inline import cython_inline; "
"sys.argv[1:] = {args!r}; "
"(lambda: cython_inline({code!r}, quiet=True))()"
).format(code=command, args=list(args) if args else [])
run_python(python, command)
def run_python_stdin(python, file_args=None, directives=None):
"""Compile and run a Python program from stdin.
import shutil
import tempfile
with tempfile.NamedTemporaryFile(suffix='.py') as f:
shutil.copyfileobj(sys.stdin, f)
file_args = [] + list(file_args or ())
run_python_file(python, file_args, directives)
def run_python_file(python, file_args, directives=None):
"""Compile and run a Python program from a file.
args = []
if directives:
for directive in directives:
args.extend(('-X', directive))
command = (
"import Cython.Build.BuildExecutable as bex; "
"bex.DEBUG = False; "
run_python(python, command)
def main():
args = parse_args()
python = args.python
if args.version:
if args.command:
run_cython_command(python, args.command, args.file_args)
if args.file_args:
if args.file_args[0] == '-':
run_python_stdin(python, args.file_args[1:], args.directives)
run_python_file(python, args.file_args, args.directives)
if __name__ == '__main__':
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment