Batchography: Batch script to automatically recompile or run a script interpreter

Hello,

In a previous blog post, I showed you how to write a polyglot Batch file that is both a Batch script and a C++ source file. When the Batch file is executed, it compiles itself (as C++).  In this blog post I am going to show you how to write a Batch file script that polls the file system periodically to see if a given input file is changed and if so, it will invoke the compiler or interpreter of your choice.

This concept is similar to what the Compiler Explorer does actually.

I am going to write a small script that keeps running your Python script automatically in a separate console window the moment you save the script in your editor. Check the script in action:

The basic idea:

  1. Set the variable last_fdate containing the last file modification date to an un-initialized value
  2. Query the file modification date/time and store its value in the fdate variable
  3. If last_fdate is different than the current file date then invoke the interpreter
    • Normally, this condition will always execute on the first run of the auto compiler script
  4. Unless the input file is modified, there will be no interpreter invocations

This is the full script source code:

@echo off

:: 
:: The Batchography book by Elias Bachaalany
::

:: Auto interpret Python scripts
::

:main
    setlocal

    if "%1"=="" goto :help
    if not exist "%1" (
        echo Input file '%1' not found
        goto :eof
    )

    set FN=%1
    set last_fdate=x

    title Batchography - Python auto re-interpreting '%FN%'

    :repeat
        :: Get the file date/time, size and attributes
        for %%a in (%FN%) do set fdate=%%~ta.%%~za.%%~aa

        :: Different attributes found?
        if not "%last_fdate%"=="%fdate%" (
            cls
            :: Re-interpret
            call python "%FN%"
        )

        :: Remember the new date/time
        set last_fdate=%fdate%

        :: Wait for a second before checking for the file modification again
        CHOICE /T 1 /C "yq" /D y > nul

        :: User pressed Q? just quit
        if "%errorlevel%" neq "1" goto :eof

        :: Repeat until user quits or Ctrl-C
        goto repeat

:help
    echo Auto Python reinterpreter takes the input file name to autocompile as an argument
    goto :eof

 

You can also download the full script from the Batchography’s book online source repository:

To learn more advanced Batch scripting techniques, make sure you grab your copy of the Batchography book.

You might also like:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.