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.
* optparse module
* howto article (IBM devWorks)
* PyMOTW optparse
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 pythonStep 2: calling the script from php
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()
# construct the cmdSources:
$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;
* optparse module
* howto article (IBM devWorks)
* PyMOTW optparse
Comments