9

I'm writing a console app using Symfony 2 Console Component, and I want to run a console clear command before (or as) the first line of my app.

I have done some research and am struggling to find if this is possible.

NickOS
  • 764
  • 1
  • 7
  • 18

2 Answers2

23

I have been looking for similar functionality. There is nothing built-in to the symfony console that can clear the screen as far as I can tell, but you can still achieve the clear behavior by using the escape code for resetting the terminal like so:

$output->write(sprintf("\033\143"));

See the post "Clear the Ubuntu bash screen for real" and "What commands can I use to reset and clear my terminal?" for a more extensive explanation of the codes, and this symfony console pull request, where I got the code from, that attempted to emulate the clear functionality.

Community
  • 1
  • 1
Onema
  • 7,331
  • 12
  • 66
  • 102
  • Even though PHP has a `shell_exec('')` it did not work for me for clearing the terminal with a `clear`. But sending `\033\143` to the output worked, which I think is the escape code for CTRL + C on a mac. – Sumeet Pareek Apr 23 '22 at 14:25
-2

As the doc says, you can use something like this:

    $kernel = $this->getContainer()->get('kernel');
    $application = new Application($kernel);
    $application->setAutoExit(false);

    $input = new ArrayInput(array(
       'command' => 'cache:clear',
    ));
    // You can use NullOutput() if you don't need the output
    $output = new BufferedOutput();
    $application->run($input, $output);

    // return the output, don't use if you used NullOutput()
    $content = $output->fetch();

As your are using a command, your command must extends ContainerAwareCommand so you can access the container and your services.

COil
  • 7,201
  • 2
  • 50
  • 98
  • 2
    Thanks for the descriptive answer, I want to clear the console not the cache. so the output from my app will start at the top of the screen – NickOS Aug 27 '15 at 10:00
  • 1
    Humm, this is not related so symfony. Just make a .sh script that call clear then your console command. – COil Aug 27 '15 at 11:54