Skip to content

Instantly share code, notes, and snippets.

@risent
Last active August 2, 2019 03:00
Show Gist options
  • Save risent/7d8744bc528fbc967ed70f7658812d1e to your computer and use it in GitHub Desktop.
Save risent/7d8744bc528fbc967ed70f7658812d1e to your computer and use it in GitHub Desktop.

Hello World In Python 10 Ways

1. general

print('Hello World')

2. sys stdout

import sys

sys.stdout.write('Hello World')

3. system call

import os

os.write(1, 'Hello World')

4 c module

  • hello.h
char * hello(char * name);
  • hello.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char* hello(char *s) {
  printf("Hello %s\n", s);
  char* buf;
  buf = (char *)malloc(strlen("Hello, ") + strlen(s) + 1);

  sprintf(buf, "Hello, %s", s);
  return buf;
}
  • hellomodule.c
#include "Python.h"
#include "hello.h"

static PyObject * hello_wrapper(PyObject * self, PyObject * args)
{
  char * input = NULL;
  char * result;
  PyObject * ret;

  if (!PyArg_ParseTuple(args, "|s", &input)) {
    return NULL;
  }

  if (input == NULL) {
    Py_INCREF(Py_None);
    return Py_None;
  }

  result = hello(input);

  ret = PyString_FromString(result);
  free(result);

  return ret;
}

static PyMethodDef HelloMethods[] = {
  { "hello", hello_wrapper, METH_VARARGS, "Say hello" },
  { NULL, NULL, 0, NULL }
};

DL_EXPORT(void) inithello(void)
{
  Py_InitModule("hello", HelloMethods);
}
  • hello.py
import hello
print hello.hello('world!')
assert hello.hello('world!') == 'Hello, world!'
  • setup.py
from distutils.core import setup, Extension

# the c++ extension module
extension_mod = Extension("hello", ["hellomodule.c", "hello.c"])

setup(name = "hello", ext_modules=[extension_mod])
python setup.py  build_ext --inplace

5. ctypes

  • hello.c
#include <stdio.h>


void hello(char *s);

void hello(char *s) {
  printf("%s\n", s);
}

/* compile to shared library */
/* gcc -o hello.so -shared -fPIC hello.c */
  • hello.py
import ctypes

hello_lib = ctypes.cdll.LoadLibrary('hello.so')

hello = hello_lib.hello
hello(b'Hello World')

Call C Printf

import ctypes
libc = ctypes.cdll.LoadLibrary('/usr/lib/libc.dylib') # libc.so.6
libc.printf("%s %d\n", "Hello World", 4)
#include <stdio.h>
#include <wchar.h>

int main() {
  wchar_t *w;
  char *c, *d;

  w = "abc";
  c = "abc";
  d = (char*)w;
  printf("wchar: %s, char: %s, char d1: %s,  \n", w, c, d);
}

6. cython

  • hello.pyx
from libc.stdio cimport printf

cdef c_hello(char *name):
    printf("Hello %s\n", name)

def hello(name):
    """Within a Cython module, Python functions and C functions can call each other freely,
    but only Python functions can be called from outside the module by interpreted Python code.
    So, any functions that you want to “export” from your Cython module must be declared as Python functions using def.
    """
    c_hello(name)

def hello1(name):
    print("Hello {}".format(name))
  • setup.py
from distutils.core import setup
from Cython.Build import cythonize

setup(
  name = 'Hello world',
  ext_modules = cythonize("hello.pyx"),
)
python setup.py build_ext --inplace
  • hello.py
import hello

hello.hello(b'World')
hello.hello1(b'World')

7. cffi (C’s Foreign Function Interface)

from cffi import FFI

ffi = FFI()
ffi.cdef("""
    int printf(const char *format, ...);   // copy-pasted from the man page
""")

C = ffi.dlopen(None)
arg = ffi.new("char[]", "World")
C.printf("Hello, %s.\n", arg)

Python CFFI LuaJIT FFI

8. swig (Simplified Wrapper and Interface Generator)

9. rust

  • lib.rs
// cargo new hello
// cargo build --release

use std::os::raw::c_char;
use std::ffi::CStr;

#[no_mangle]
pub extern fn hello(s: * const c_char) {
    unsafe {
        let slice = CStr::from_ptr(s);
        println!("Hello {}", slice.to_str().unwrap());
    }
}
  • Cargo.toml
[package]
name = "hello"
version = "0.1.0"
authors = ["risent <[email protected]>"]

[dependencies]


[lib]
name = "hello"
crate-type = ["dylib"]
  • hello.py
import ctypes

hello = ctypes.cdll.LoadLibrary("./hello/target/release/libhello.dylib")

hello.hello('World')

10. boot.Python (C++)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment