Running for loop terminal commands in Jupyter

A possible hackish solution could be to use eval and let bash execute a string.

for idx in range(10):
    !eval {"python process.py --filename /Users/images/{image}.jpg".format(image=idx)}

Use the glob module and maybe subprocess instead of !. A simple glob.glob("path/*.jpg") will let you iterate over all pictures.

from glob import glob
from subprocess import check_call

for i in glob("/Users/images/*.jpg"):
    print("Processing:", i)
    check_call(["python", "process.py", "--filename", i], shell=False)

Using ! or eval is never a good idea - the command may fail silently.


The ! simply indicates that the following code will be executed in the terminal.

So one option is just to code your statement in bash. It's not quite as easy as Python, but you can accomplish the same task like this:

! for file in /Users/images/*.jpg; do python process.py --filename /Users/images/$i; done

It's a for loop, but not a Python for loop.

Alternatively, consider going back to the source code of process.py and modifying it so that it will loop through the files in a directory. This can be done easily enough with the os.listdir function.


No need for subprocess or format. Something as simple as:

for idx in range(10):
    !python process.py --filename /Users/images/{idx}.jpg

works for me.