2

I am trying to find all .js files in directories and gives it as arguments to python. I could collect all the files with .js using bash command find . -name "*.js", but I don't know how to give these information to python. I don't want to send file name one by one. I want to send as a list the python code that handling arguments is following.

import argparse

argparser = argparse.ArgumentParser("sh test")

argparser.add_argument("js_file", type=str, nargs ="+", help="js file names")

args = argparser.parse_args()
for file in args.js_file:
    # do something
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
taegyun kim
  • 119
  • 1
  • 9
  • 2
    You can find all files matching `*.js` in Python too: https://stackoverflow.com/questions/2225564/get-a-filtered-list-of-files-in-a-directory – Selcuk Oct 04 '19 at 03:06
  • Related https://unix.stackexchange.com/questions/389705/understanding-the-exec-option-of-find – OneCricketeer Oct 04 '19 at 03:09
  • If there are no spaces in the filenames, this is just `python my_script.py *.js` – wim Oct 04 '19 at 03:18

3 Answers3

1

If you have GNU find you can use -exec + to call a command with all the matching file names in one go.

find . -name '*.js' -exec script.py {} +

If not you can get the same behavior with find | xargs.

find . -name '*.js' -print0 | xargs -0 script.py
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

You can use subprocess.run from a python script to do this:

import subprocess
cmd  = 'find . -name "*.js"'

p = subprocess.run(cmd, shell=True, capture_output=True)
files = p.stdout.decode().split()
print(files)
Lord Elrond
  • 13,430
  • 7
  • 40
  • 80
0

Given that foo.py is your python script, you can use this:


python  foo.py `find . -name "*.js" | tr '\n' ' '`

Rasheed
  • 101
  • 5