0

I want to execute a python script from within a for loop.

What I tried was more or less the following:

input_dir_parent='/home/.../parent_folder/'
for input_directory in os.listdir(input_dir_parent):
    python process.py --input_dir  input_directory

So I want to pass a variable (that changes after each iteration) from the for-loop as an argument to the process.py script. This does not work however. The input_directory after --input_dir will not be a reference to the input_directory but just an 'independant' arguement (in this case it will be handled as a string 'input_directory'). Is there another way to do what I want?

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Take a look at the Subprocess Module https://docs.python.org/3/library/subprocess.html – Marco D.G. Sep 23 '21 at 10:17
  • `python process.py --input_dir input_directory` is not valid Python syntax... Python is not Bash. – juanpa.arrivillaga Sep 23 '21 at 10:19
  • 1
    why not import process.py and call operation using a function. it will be more easy and useful to debug – Pavan Kumar T S Sep 23 '21 at 10:20
  • 1
    As noted, you can call a subprocess using the `subprocess` module. Note, though, that *usually* it makes more sense to use your script *as a module*. Wrap the code that gets executed in a function that you can reuse – juanpa.arrivillaga Sep 23 '21 at 10:20
  • 1
    I assume this is tagged `argparse` because `process.py` uses that to handle commandline. Otherwise this isn't an `argparse` problem. It is also tagged `jupyter-notebook`. Is that where you are running this? `jupyter` has `magics` for running scripts, `!` and `%run`. And the `magics` allow you to use OS like `$` and `{}` to substitute variables into the calling expression. https://stackoverflow.com/questions/69153603/can-i-use-a-run-inside-of-a-for-loop – hpaulj Sep 23 '21 at 15:36
  • Thanks everyone for the help. I think i can figure it out from here. I also realized that the approach is flawed from the beginning, so i will probably also solve it in a different way afterwards:) – Philipp Steiner Sep 24 '21 at 09:08

0 Answers0