PHP and Python are two of the most widely used website programming languages. And I think Python is the best glue for concatenating different languages in one project. Recently, I used these two languages frequently. I want to summarize one particular function which can execute external command. For example, sometimes we need to process a data by other program or script. Under this scenario, we should use a function to call external command and execute it to do further analysis. I am only familiar with these two, so I can introduce them in details.

PHP

Before introducing the execution function, we would better to pay attention to the settings in php.ini. This file have some configurations to control the execution of external command. Normally, in Ubuntu, the php.ini is located in /etc/php5/apache2/php.ini if you are using Apache as front server. These settings we should note:

max_execution_time = 30
safe_mode = Off
disable_functions = pcntl_alarm,pcntl_fork,...

If we want to wait the external program until it is end, we should pay attention the max_execution_time. Sometime, the time may exceed the default time limit. The second one is safe mode which can run the program located in some specified directories. The third one is some dangerous command you want to disable, such as fork, rm, …, etc.

exec(), system() and passthru()

These three function can be used to execute external program in PHP. You can see the usage of these three function in PHP manual. The difference between these is:

They have slightly different purposes. exec() is for calling a system command, and perhaps dealing with the output yourself. system() is for executing a system command and immediately displaying the output - presumably text. passthru() is for executing a system command which you wish the raw return from, presumably something binary.

from stackoverflow

I always use exec() function, because it can easily catch the execution results of the system. And also I suggest you not use any of them. They all produce highly unportable code.

Python

There are two ways to call external commands. os.system(), subprocess.Popen().

Subprocess is based on popen2, and as such has a number of advantages - there's a full list in the PEP here, but some are:

  • using pipe in the shell
  • better newline support
  • better handling of exceptions

from stackoverflow

Pay attention: when using subprocess.call() when the external commands have several arguments, you need to set the parameter shell=True.