Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running for loop terminal commands in Jupyter

I know how to run command line in Jupyter : using ! For example, run an image file 2.jpg on Python process.py

! python classify.py --filename /Users/images/2.jpg

Question is, how to process all files of a folder in iteration way (idx) in Jupyter cell, something like this:

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

Thanks

PS: I tried path , did not work:

for i in range(1,10):
    cur_path = '/Users/images/'+str(i)+'.jpg'
    path = os.path.expanduser(cur_path)
    print(i,path)
    ! python process.py --filename path
like image 294
Bill Ancalagon the black Avatar asked Oct 24 '17 21:10

Bill Ancalagon the black


3 Answers

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.

like image 171
krassowski Avatar answered Sep 22 '22 13:09

krassowski


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)}
like image 32
Ankur Ankan Avatar answered Sep 19 '22 13:09

Ankur Ankan


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.

like image 28
Keelan Fadden-Hopper Avatar answered Sep 19 '22 13:09

Keelan Fadden-Hopper