Calling PHP code from Python

Many years ago our organization had a dying change management system. As the organization began looking for a new enterprisey system, our team felt it was a good time to roll out a release management system for our own process.

We decided to roll our own solution because at the time we were the only team using release management, and this wasn’t a priority for the organization to support.  Built on PHP and JQuery, it did what we needed. Though as we move towards the future, we have been seeing cracks that need to be filled.

One crack is that our architecture design wasn’t great. Now updating the system or rolling out new features has become difficult. We are re-architecting the solution, but because of old design considerations we haven’t been able to  figure out how to add API services so  we can be more flexible on the front end, including building a mobile app.

As I was thinking about how much I want to roll out a mobile version of our site, I began to think about how we could use Python, one of my current favorite languages, and particularly flask, to bolt on a solution to provide api services. My thoughts moved to two places-

  1. Building our api services in PHP.  I really have no experience in this, so it hasn’t been an option I’ve explored.
  2. Building a fully separate microservice in Python, duplicating some of our workflow engine rules and SQL queries.  This scares me. Having essentially two separate solutions would be a maintanance nightmare.
  3. Building a light framework in Python that hooks into existing PHP code. Using the existing PHP code, so one update affects both solutions, and having a powerful Python based api service to feed a mobile app.

So I have started looking into this. This is the very beginning, faithfully calling PHP code from within Python.



Our PHP function(s). These functions could have parameters.

There’s nothing special to do on this side. Write some standard PHP, it can or doesn’t have to return a value. Our function returns some text.

Our return value would be what is passed back to the Python call.


function readTheFile(ourFile) {
 $myfile = fopen($ourFile, "r") or die("unable to open the file");
 return fread($myfile, filesize($ourFile));



Here I’m simulating data in a file, but in the function above we could return data from anywhere.

and things
and other things

Here’s where the magic happens.

We’re creating an OS process to open the file with PHP, and we have the actual PHP call as a block of text that will be executed.

In php(code), we take in a small amount of PHP code that actually calls the PHP function from the file above. It opens up a program called “php” and pipes the input, output and stderr back to us in Python using subprocess.Popen(). In Python 3.5 it’s recommended to use run(), we don’t here.

We then call subprocess.communicate, and send our PHP code block defined in the Python code, encoded in a byte stream, through stdin to the PHP call made with subprocess.Popen(). the return result comes back in our o variable.

When we’re done, we clean things up by trying to kill the subprocess, here defined in p. At the end, we return the values received from the PHP code in o.

Stored in the code variable we have our PHP code that echoes the return value of readTheFile() PHP code back to o.  We could make our include and readTheFile() parameter both variables passed in, which we will do at some other time.

We then call our Python defined php() function, passing in the Python defined PHP code block as a parameter. This starts the process of opening the subprocess “php”, piping the byte encoded “code” text block to that subprocess, and then getting the echoed value back and stored into the res variable.

After that we can do what we like with the information returned, process it further or in our case printing it out.

import subprocess

def php(code):
 p = subprocess.Popen(['php'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)

 o = p.communicate(code.encode())[0]
 os.kill(, signal.SIGTERM)

 return o

code = """<?php
 echo readTheFile('dict.txt');


res = php(code)
print("And here is the result of the PHP call yo {}".format(res))

I hope that was more than clear as mud!

Next time we will look at further parameterizing our Python code to move towards a framework. After that we will explore building an API service around this code.

Making Promises. Javascript ES6 async for humans.

Javascript ES6 adds the ability to use the Promise.  Just as its name gives away, a Promise allows code to call an asyncronous function without regards to when that function will return code. It “promises” a result at some point in the future.

Here’s the example I keep seeing around the innerwebs:

var promise = new Promise( resolve, reject ) {
  /* Here is what I want to do for you
     This could be done asyncronously and I'll let you know
     when this is done.
     Done could mean I couldn't finish */
  if (/* everything is awesome */ ) {
    resolve( 'Heres your datas' );
  } else {
    reject( 'I dont knows' )

// Here's a way to call it, result and err would be callback functions
promise.then( result, err );

//long form
promise.then( function( result ) {
  console.log( result );
}, function( err ) {
  console.log( err );

Not sure about you, but I don’t like the terminiology I’ve found in most write ups on the Promise. I’m a human, and I don’t “resolve” or “reject” a promise I make. I can’t “error” on a promise. And to me, a “result” absolutely COULD be an “error”, just not the result we want.

This really messed with my brain while trying to understand Promises. Seriously. Like I said, I’m a human and speak human, American English.

So how would I explain it better? Not sure I can, but here’s where I would start.

var myPromiseToYou = new Promise( kept, broken ) {
  if ( /* did we do what we promised? */ ) {
    kept( 'heres your datas' );
  } else {
    broken( 'too bad, soo sad' );

//now we call it, simply
myPromiseToYou.then( keptPromiseResultCallback, brokenPromiseResultCallback )

//long form
myPromiseToYou.then( function ( keptPromiseResult ) {
  console.log( keptPromiseResult );
}, function( brokenPromiseResult ) {
  console.log( brokenPromiseResult );

So what’s this actually doing?  We’re putting some anonymous functions inline in place of the keptPromiseResultCallback and brokenPromiseResultCallback.
The code passes those functions back (callback) into the kept and broken parameters in the original definition of the Promise. So when the original definition says “kept(‘Heres your datas’)”, what it’s actually saying is “console.log(‘Heres your datas’)”.

It would like like this if we subbed in the inline functions from above for ‘kept’ and ‘broken’.

var myPromiseToYou = new Promise( ) {
  if (/* did we do what we promised? */) {
    //kept('heres your datas');
    console.log( 'heres your datas' );
  } else {
    //broken('heres your datas');
    console.log( 'too bad, soo sad' );

This is barely the tip of the iceburg with the Promise. You can stack a bunch of catch() and then()s around to give you some deep power. There’s also Promise.all and other methods you can call.

I hope reading this made the basic premise of a Promise more clear. I know writing this helped me!

Here’s a good link to a Google write up on the Promise in ES6

tkinter with Python, the basics

As I’ve stated before, I’ve always loved the command line. It’s where I’ve been most comfortable.  I cut my chops writing C and assembly, and really started my career writing Mumps/Cache code all from the command line.

Recently I’ve been challenging myself to get into writing for the GUI. I have a few Udemy courses lined up for android development, and promised myself I’d write a gui for at least one of my Python experiments.

While researching Python GUIs, I’ve settled on tkinter as my weapon of choice. The documentation, as far as I’ve seen, is scattered and release dependent.  So cobbling the minimum together I’ve come up with the following framework to get at minimum a window with a menu attached.

Feel free to use the code to start your journey!

# different versions have diff tkinters
# let's do right by this
    import tkinter
except ImportError:
    import Tkinter as tkinter

# placeholder for this example
def hello():

# from the docs
# The Tk class is instantiated without arguments.
# This creates a toplevel widget of Tk which usually
# is the main window of an application.
# Each instance has its own associated Tcl interpreter.
mainWindow = tkinter.Tk()

# Here are our main window params, including
# the window title, how big is the window
# and some padding, because
mainWindow.title("Main Window Title")
mainWindow['padx'] = 10

# our main menubar is attached to the window created above
# we don't give this a name or anything, it's the base menu
# we'll use to attach our real menus
main_menu = tkinter.Menu(mainWindow)

# Here's the good stuff. We create a menu from class
# and attach it to the main_menu menubar.  we add our commands
# to each menu item as a cascade. We can do this for each
# individual menu
main_util_menu = tkinter.Menu(main_menu, tearoff=0)
main_util_menu.add_command(label="Do Some Stuff", command=hello)
main_util_menu.add_command(label="Doing Other Stuff", command=hello)

main_file_menu = tkinter.Menu(main_menu, tearoff=0)
main_file_menu.add_command(label="Save", command=hello)
main_file_menu.add_command(label="Open", command=hello)
main_file_menu.add_command(label="Exit", command=main_menu.quit)

# Now we just need to add each menu, in order
main_menu.add_cascade(label="File", menu=main_file_menu)
main_menu.add_cascade(label="Database", menu=main_util_menu)

# set up the main window to use our menubar

# redraw and start the fun!

Building a Dynamic Menu System for Python3

I’m rubbish at GUI work. When I can, I limit what I do to the command line. Having a nice menu is always key for me so I can group a few utilities in a single call and not have to just call functions directly from the command line. So I’ve been thinking a lot about how to build a reusable menu system for Python. Something that can go at least two levels deep, and then at the final level be able to execute code. Something that, with little modification, I can make work with any utility app I write.

I came up with the solution described in this article. It makes use of the fact that Python is object oriented, and that functions are first class objects. What that means is, we can pass functions around as we would data as well as execute them.

When we want to execute a function we call it with parenthesis like this

#define my function first
def my_toy_function():
    print(‘We would do stuff here’)

#executing the function, which would print ‘We would do stuff here’

but if we just want a REFERENCE to the function, to the memory location that points to the function, we can pass the function name WITHOUT PARENTHESIS like this

#passing the reference to the function
some_other_func_name = my_toy_function

What good is this? As you will see in my code, this allows me to store a reference to a function in a dictionary, so that I can call the function later. We can also create decorators which actually return functions (references to functions!) based on the execution of code.

In the above example I can now call the my_toy_function code two ways

#calling my_toy_function directly, which prints ‘We would do stuff here’

#calling the passed reference, which prints ‘We would do stuff here’

Crazy, right? As I said above, you can also use this to create decorators, which we will not cover here.

Let’s dig in!

This example is not too pretty, I don’t do any error catching yet, but I think it’s a good start.

We’ll start looking at some supporting pieces, like our dictionaries that have tuples nested in them. The me_menu_dict is a second level menu dictionary. We’ll get to that in a minute.

The main_menu_dict is just as it says, our dictionary for the main text screen.

main_menu_dict = {
    '0': ('Me', me_menu_dict),
    '1': ('Quit', 0)

It has string keys to prompt the user to choose a selection, this way we don’t have to do the int conversion on the input function.

The tuple value is the name of the sub-menu (eg. ‘Me) and a pointer to the dictionary holding the sub menu (eg. me_menu_dict). I’ve named the dictionaries NAME_menu_dict, and the NAME is the same as the index 0 string in the main_menu_dict tuple

('Me', me_menu_dict),

I could have embedded the sub menu directly in the main_menu_dict tuple, but wanted it to be cleaner and easier to maintain.

With the embedded dictionary called, it actually embeds the sub-dictionary in the original for me at run time. If I did a print statement on the values of the main menu dictionary it would look like

‘0’: (‘Me’, {
        ‘0’: (‘Profile’, get_profile), 
        ‘1’: (‘Rank’, get_rank), 
        ‘2’: (‘Tokens’, get_tokens)})

The sub menu is magical. It contains a call to the functions get_profile, get_rank and get_tokens. Otherwise it acts just like the main menu – a dictionary with a string key and tuple value.

me_menu_dict = {
    '0': ('Profile', get_profile),
    '1': ('Rank', get_rank),
    '2': ('Tokens', get_tokens)

Here are the functions referenced in the sub menu tuple. See above there are no parens? This is so we have a REFERENCE and don’t actually CALL the function.

def get_profile():

def get_rank():

def get_tokens():

Here’s our main text menu function. I’ve pulled out some of the new lines and things I added to just get to the good code. Instead of explaining it here, I’ve added comments to the code

def text_menu():
    while True:
        print('Main Menu')
        for k,v in sorted(main_menu_dict.items()):
            print("\t{}. {}".format(k, v[0]))

        selection = input('Please enter the number of your selection: ')

        if selection == '6':
            while True:

        # going in one level to get the menu attached to the main menu
        # this is actually just the key to that submenu
        print("\n{} Menu\n".format(main_menu_dict[selection][0]))
        # The dict doesn’t give us data sorted
        # Dicts are called by key so order isn’t a problem.
        # but we WANT it sorted by key in this case 
        # so we wrap the main_menu_dict in a sorted() call.
        for item in sorted(main_menu_dict[selection][1]):

            """this is a bit more complex
            because we embedded dicts in dicts in tuples

            here we go
            1. main_menu_dict[selection] 
               This returns the main menu selection key/val tuple
                   ('Me', me_menu_dict)
               Which remember expands to the full dictionary
                   (‘Me’, {
                           ‘0’: (‘Profile’, get_profile), 
                           ‘1’: (‘Rank’, get_rank), 
                           ‘2’: (‘Tokens’, get_tokens)

            2. main_menu_dict[selection][1] 
               returns the embedded MENU in the main menu tuple
               which in main menu is the call to me_menu_dict in the tuple
                   {‘0’: (‘Profile’, get_profile), 
                    ‘1’: (‘Rank’, get_rank), 
                    ‘2’: (‘Tokens’, get_tokens)}

            3. main_menu_dict[selection][1][item] 
               returns the value from the embedded menu - our next tuple
                   (Profile, <function get_profile at 0x7f08ee5b1840>)

            4. main_menu_dict[selection][1][item][0]
               is the first value in the tuple 
               Which is in the VALUE of the embedded menu

            5. If we grabbed the second index in the tuple to
               it would return the pointer to the function
                   <function get_profile at 0x7f08ee5b1840>
               See how that’s a pointer to a memory location 
               of the function? In this case 0x7f08ee5b1840

            # here we just print out the keys to the sub menu. 
            # See number four above.
            print("\t{}. {}".format(item, 

        # Our sub menu selection 
        # We’re out of the for loop above, which just prints our menu.
        # now we want to know where the user wants to go
        print("Please enter the number of your selection.")
        new_selection = input('Hit enter to return to main menu: ')

        if new_selection == '':
            """So now we have our last selection 
               This is from the SUB menu. 
               Let's go ahead and execute the function
               This is a cool thing about Python, 
               in the dictionary we are storing a pointer 
               to each function, but not executing it since
               there are no parens after the function name. 
               first class objects! So when we call below, 
               we add the parens and BAM! function call.

That’s it, a dynamic menu system. If I want to add items to the main menu, I add them as dictionary items with
Key = number as string
Value = tuple(menu name to print, submenu to call)

Then add a submenu in a similar format
Key = number as string
Value = tuple (menu name to print, function to call)

As I said, there’s still some work to be done. For one, we need to catch some exceptions. We also need to pretty up the printing. Last, I’d like to be able to have a menu item on the main menu that calls a function, not possible with the current config.

But as it is, it’s usable and makes my life easier!