I have found a lot of documentation on how to run Drush commands from code, but I'm specifically looking on how to run a Drupal Console command from code.

I have some experience in Symfony and I know how to run a Symfony command from code. Since a Drupal console command extends on Symfony command, I thought this should be rather easy. Simply following this tutorial doesn't amount to anything though.

I am trying to run a command in a hook_cron() implementation in a custom module.

  • 1
    Please elaborate why you would downvote my question. I've spend close to an hour in the code and over an hour on the internet for a solution, but I just can't get there.
    – Loek
    Commented Jun 28, 2017 at 13:35
  • What if you use the php functions exec() or shell_exec() ? I haven't done it before but it's the first thing I would try. Commented Jun 28, 2017 at 15:55
  • It's weird how you can become so fixated on doing it 1 way that forget about the other, way easier ways.. Will accept as answer if you add it ;)
    – Loek
    Commented Jun 28, 2017 at 16:11
  • 1
    Thanks. I've added the answer with refernces to the php docs to help others as well Commented Jun 28, 2017 at 16:24

3 Answers 3


Try using the PHP functions exec() or shell_exec().

  • 1
    But do so carefully and responsibly.
    – Kevin
    Commented Jun 28, 2017 at 17:01

Run shell commands via the Process class available in the Symfony framework.

From the Symfony docs:

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process('ls -lsa');

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);

echo $process->getOutput();

The component takes care of the subtle differences between the different platforms when executing the command.

Replace the ls -lsa command in the Process() constructor with your Drupal console command.

  • This is more in the way I was looking for indeed. Sticking with exec for now since there aren't any parameters and the command is fixed, but this is nice for better handling of your commands.
    – Loek
    Commented Jun 28, 2017 at 17:30
  • Thank you, this approach looks good. There is a function drush_shell_exec_interactive which shows more imformation for interactive commands, like drush cim -y. But it is deprecated. I am still looking for a replacement for this function.
    – milkovsky
    Commented Sep 30, 2020 at 11:39

In D10 at least you can now run e.g.:

  $modules = ['redis'];
  \Drupal::service('module_installer')->install($modules, TRUE);

So many things you would want to do with Drush now can be called directly through Drupal services.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.