Wednesday, June 4, 2008

execute linux command using Perl, Python, PHP

Those who program in Linux often need to execute/run linux commands from programs/scripts.

Using python you can execute linux command is the following way:

import os
os.system('ls -lt')



If you use Perl, you can do it in the following ways:
1. system(mkdir $folder);
2. qw(mkdir $folder);
3. $temp = `mkdir $folder`; #back ticks
4. exec($command);

If you use back ticks or qw, $? will be set if any error occurs. So you can use it like this:

qw(rm $filename);
if($?) {
print STDERR "error deleting file\n";
}


There are also several options available to run linux commands using PHP. Take a look at here for detals: http://us2.php.net/manual/en/ref.exec.php

No comments: