What is the best way to run all Python files in a directory?

To run a python file in a directory, we generally use the python or python3 command. However, it only runs a single file at a time. But executing one file each on a shell script seems cumbersome. Therefore, we must come up with a way to execute all files present in a directory simultaneously.

There are two ways to do this in a shell program −

  • Using loops in bash

  • Using xargs

Using Loops

The fastest and easiest way to run all Python files in a directory is to use loops. You can use bash to do this for you.

Bash is a command-line interface shell program that is used in Linux and macOS. It is developed by Brian Fox as a successor to the Bourne Shell, hence, an acronym for Bourne Again Shell.


For example, create a new file called run_all_py.sh and write the following in it −

for f in *.py; do python"$f"; done

Now, run the file using the following command −

$ bash run_all_py.sh

Using xargs

xargs is only available on UNIX. It can be used in parallel to execute these files. This is very helpful in today’s multi-core processor systems.


To execute all files in a directory, use the following command in the shell −

$ ls *.py|xargs -n 1 -P 4 python

Updated on: 19-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started