use php to call python cmd line tool

Step 1: writing the python cmd line tool
Here, the optparse module does most of the heavy lifting. Note that optparse doesn't allow to set options as required (this is an oxymoron, according to the docs), so we'll handle it ourselves.
#!/usr/bin/env python
import optparse, sys

def main():
p = optparse.OptionParser()
# define options
p.add_option('-u', '--user', dest = "user", help = "User account name")
p.add_option('-p', '--pwd', dest = "pwd", help = "User account password")
# parse cmd line string into options and arguments datamembers (raises exceptions)
options, arguments = p.parse_args()
# check if required args are present
if options.pwd is None:
print "No pwd provided."
sys.exit(2)
# do sth
print "user = " + options.user
sys.exit(0) # success

if __name__ == '__main__':
main()
Step 2: calling the script from php
# construct the cmd
$cmd = "python ./cliscript.py -u me -p mypwd";
$ret = null; # return value

# execute cmd
ob_start();
passthru($cmd, $ret);
$out = ob_get_contents();
ob_end_clean();

# show cmd results
echo "\n\nStdout data:\n";
echo rtrim($out); # make sure extra whitespace is removed
echo "\n\nReturn val:\n";
echo $ret;
Sources:
* optparse module
* howto article (IBM devWorks)
* PyMOTW optparse

Comments

Popular posts from this blog

Handling control characters (escaping) in python for json and mysql

python port sniffer with pcapy and impacket

Django field, form and model validation process