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
3

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.