How to use Laravel with Python and the command line

Laravel is a fantastic framework for developing state-of-the-art web applications.

Python is terrific for data processing.

So how to leverage the best of both worlds?

Last week I have been experimenting with a Laravel sideproject performing sentiment analysis on a Twitter stream.

Turns out, the best of-the-shelf package for sentiment analysis of microtexts is VADER, a Python package.

According to VADER’s authors it “is a is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media”.

That’s a mouthful for saying that it takes a short text (like a tweet) and returns a sentiment score.


So back to how to use Python with Laravel. There are a number of ways you could go about that:

  • look for a Laravel or PHP port of the Python package. I found some, but I was not impressed. They either didn’t work with my Laravel installation or were simply outdated. Also, I was concerned with performance – I rather offload the heavy lifting to Python.
  • write a PHP port of the package yourself. This would be a complex task, and I also wouldn’t benefit from future updates to the official VADER package.
  • wrap the Python script in a Python-powered REST API with Flask which can be called from the Laravel app. But I prefer to keep things as simple as possible. I.e. setting up Flask would require me to perform additional server configuration. More complexity = more things that can go wrong = more time spent on maintenance. (It would be an interesting approach for a sentiment-analysis microservice solution though :)).
  • let Laravel write the texts to storage such as a .txt file or a mySQL database. Periodically analyze unprocessed records with the Python script. This works great with massive datasets, but also means Laravel has little/no notion of what the Python script is doing.
  • interact with the Python script callable via the command line. And that’s what I ended up doing.

A few notes

This blog post focuses on the “Using Laravel with Python” part. If you want to know more about listening to a Twitter stream with Laravel, be sure to check out Spatie’s Laravel Twitter stream package. It works like a charm.

Also, make sure to sanitize the Tweet texts before processing them.

The simplest version

My initial solution passes a single sanitized string from Laravel to the Python script using the command line, and the Laravel app then parses the output from the command line.

The Python script:


import sys
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

analyser = SentimentIntensityAnalyzer()

It’s not well-documented, but Laravel actually does include a Symphony Process component for running commands.


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

$text = 'The text you are desperate to analyze :)";
$process = new Process("python3 /Path/To/ \"{$text}\"");

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

echo $process->getOutput();
// Result (string): {'neg': 0.204, 'neu': 0.531, 'pos': 0.265, 'compound': 0.1779}

The improved version

There is room for improvement though. So I refined the flow a bit, and the script can now take an array of strings at once. But since it is impossible to pass objects as command line parameters, it is passed as a JSON encoded string.


// $json = an encoded JSON string
$process = new Process("python3 /Path/To/ {$json}");

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

dump(json_decode($process->getOutput(), true));

The Python script, now handling an encoded JSON string and outputting a new encoded JSON string:


import sys
import json
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer


analyser = SentimentIntensityAnalyzer()

for item in data:
    item['sentiment'] = analyser.polarity_scores(item['text'])
    item.pop('text', None)


Another trick for reading command line output with Laravel

There is one other method I used for reading command line output back into Laravel: accessing the output buffer.

Let’s say I have a black-box Laravel/PHP function interacting with the command line. A function which I cannot or do not want to modify for system architecture considerations (i.e. separation of concerns).

I can get its command line output by wrapping it in ob_start() and ob_get_clean(), like this:

$output = ob_get_clean();

You can find more information on accessing the output buffer here.

Access the full source code

Get access to the full source code using the form below.

You’ll get the full Laravel project along with installation instructions.

The project leverages Laravel jobs, the queue worker, Eloquent/MySQL and console commands via artisan. A nice read ;).

Check it out now.

13 Replies to “How to use Laravel with Python and the command line”

  1. Hello sir, I have read your post, but I don’t know how to run your project, would you mind showing me how to run it, maybe a instruction video, or more details explanation about the way you run your project
    Really appreciate that, thank you.

      1. Hello Sander,

        Thank you for your reply, because my english is not very good at all, so I might not quite understand all what you say in the read me file. I’m doing my thesis, and my project is just same same like yours. So, do you mind or have time to make an instruction video for me, really appreciate if you do that. But in case you don’t have time, can you explain more about the instruction, step by step.

        Thanks again

  2. Hi Johnny Joe,

    I have no plans for recording instructions.

    This blog post and app are intended for intermediate and advanced Laravel developers. If you’re just starting Laravel development, be sure to check out the official docs at

    If you’re comfortable with the basics of setting up a new Laravel app… Your English seems good enough to interpret the file.
    I’ll include an excerpt for you and other readers below. If you get stuck trying this, let me know where precisely you get stuck

    Here it is:

    This project provides a few console commands:

    – php artisan sentiment:string {string}
    – php artisan sentiment:json {json_string}
    – php artisan twitter:listen {for}

    If you want to study the code, I’d recommend to start at the `app/Console/Commands` folder.

    ## Installation

    – Create a MySQL table for this project
    – Rename or copy `.env.example` into `.env`
    – Configure database connection in `.env`
    – Configure Twitter API keys in `.env`
    – Run `php artisan migrate`
    – Make sure `python3` is on your PATH
    – Install the [VADER python package]( (via pip)

    1. Hi Sander

      Thanks for your reply. So in case you don’t have time for recording instruction for me, it’s okay man, I’ll try to understand your readme file and do as you say, if I get stuck in any step of it, I will ask you, hope you don’t mind if I ask too much :). By the way, can I have your email? It’s more convenience if we contact through the email, right? Here my official email: (blocked by Sander). Hope you reply me soon

      Thank you

        1. Hey Sander . i did all way to share and only i reiceved is python code … I don’t know what benefir tutorial you publish . Could you send full project and function for me . Thanks for your share !

          1. Sorry to hear the benefits of this tutorial are not clear to you.
            As the post title says, it’s about
            “How to use Laravel with Python and the command line”. It includes Laravel PHP and python code examples.

            I see you have signed up to the newsletter to receive a zip file (see your mail) with the project source code.

            The project has been crafted with care and took me about 20 hours of research and development. It has been used and tested by many other Laravel enthousiasts.

            If the zip does not contain a full source, could you please send me a list/ screenshot of the zip’s root folder?

    1. Hi Vo Nguyen,

      Thanks for sending the screenshots. I have looked at it and all seems fine, all necessary files are included. You forget to mention that there actually is a complete Laravel application included in the source files, so I was surprised by that. 🙂

      The main application is developed in Laravel, that’s why the other 98% are not Python files (.py). It only leverages two python (.py) scripts, which indeed are also detailed in this tutorial. But these two python scripts are all that’s needed, as they perform some quite heavy lifting (sentiment analysis) using the VADER library (make sure it’s installed – see the included readme file).

      If you’re not yet comfortable with Laravel, I suggest to study other Laravel projects first, as this tutorial is advanced level.

  3. Hello Sander,
    Thank you for tutorial.
    I encounter some issue : I set up a virtual environment for python where i put my script which call some pip lib in lib\site-packages.
    My script file works well when called from shell but when it is called by laravel Command it failed with ‘module not found’.
    I guess it is an issue with the import and sys.path as the script is not called from a folder in the virtual environment.
    I am a beginner on that : do you know how to solve that?

    1. I would like to clarify my post:
      My script file in the virtual environment call a library i downloaded with pip and import in the script file. This library ‘lamba’ imported causes an error, moduleNotFoundError : no module named ‘lambda’. This module is however present in the lib/site-packages and its parent folder is in the sys path. My script file is at the top of project folder and works well when called from python shell.

      1. Hi David,

        My Python skills are a bit rusty, but here are a few things you could check:
        1) make sure Laravel is executing the command in the intended virtual environment by executing “pip -V” from within Laravel (
        2) (related to the previous) make sure Laravel calls the intended Python binary by executing “which python” (or “which python3”) from Laravel. It should give the same output as calling it directly from the commandline.
        3) try setting the import statement as an absolute path instead of a relative one.

        Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *