1

I picked up a script (script1.py) from another dev which uses the flags module from absl. Basically it is ran as such:

python script1.py --input1 input1 --input2 input2

I currently have another script (script2.py) which generates that input1 and input2 for script1 to run. How can I actually pass the args over to script1 from within script2? I know I have to import script1 but how can I then point it to those inputs?

2
  • 1
    you can either use those parameters in function which is being ran, usually main() or you can call something like subprocess to run the script with subprocess.Popen() and pass arguments there. Commented Sep 9, 2021 at 22:26
  • 1
    It will depend on how the arguments are parsed in script2.py. To better answer your question, could you provide more details about the file? Commented Sep 9, 2021 at 22:28

1 Answer 1

1

Use the Python subprocess module for this. I am assuming that you are using a version that is 3.5 or newer. In this case you can use the run function.

import subprocess

result = subprocess.run(
    ['python', 'script1.py', '--input1 input1', '--input2 input2'],
    capture_output=True)

# Get the output as a string
output = result.stdout.decode('utf-8')

Some notes:

  1. This example ignores the return code. The code should check result.returncode and take correct actions based on that.
  2. If the output is not needed, the capture_output=True and the last line can be dropped.

The documentation for the subprocess module can be found here.

A alternative (better) solution

A better solution (IMHO) would be to change the called script to be a module with a single function that you call. Then python code in script1.py could probably be simplified quite a bit. The resulting code in your script would then be something similar to:

from script1 import my_function

my_function(input1, input2)

It could be that the script from the other dev already has a function you can call directly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the input! I will have to give this a try but yeah this makes sense and I think it will work, sadly I myself cannot make changes to script1.py, but I will check with the other dev if it can be updated, as that will simplify this quite a bit.

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.