- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Example
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.
Example
To execute all files in a directory, use the following command in the shell −
$ ls *.py|xargs -n 1 -P 4 python