viki
viki

Reputation: 157

Calling one Python script inside another with command-line arguments

I have two independent Python scripts that work independently by supplying relevant arguments. Now I need to call python1.py in python2.py and pass the relevant parameters that are accepted by python1.py.

Is this the right approach?

  1. Create a method call_python1(args) inside python2.py
  2. Use subprocess module to execute python1.py
  3. Call call_python1 in the main method of python2.py

Note: Both scripts should keep working independently as they are now.

Upvotes: 1

Views: 1499

Answers (2)

john-hen
john-hen

Reputation: 4846

This is the right approach under the described circumstances: that both scripts should continue to work as independent command-line tools. (If not, it would be advisable to import as a module.)

In this case, one would typically want to make sure the other script is executed by the same Python interpreter, in case several different versions are installed. So in python2.py, and possibly inside that call_python1 function, you would start the subprocess like so:

import subprocess
import sys

subprocess.run([sys.executable, 'python1.py', ...])

Here sys.executable gives "the absolute path of the executable binary for the [current] Python interpreter". The ellipsis denotes the additional command-line arguments to be passed, added as separate strings to the list.

Upvotes: 2

Giovanni Patruno
Giovanni Patruno

Reputation: 763

You can surely invoke the python1.py using a subprocess but I would avoid this kind of invoking since you will need to manage the subprocess lifecycle (OS permissions, check the status code of the subprocess, eventually the status of the process, etc.).

My advice is to convert python1 to an importable package (see the official python documentation for more information).

By doing so you will have a set of benefit lik: explicitly defined requirements, version, etc. It will be eventually reused by a python code that doesn't want to use subprocesses.

Upvotes: 0

Related Questions