Abhi
Abhi

Reputation: 349

Passing arguments to argparse from subprocess.Popen

I am trying to call a script using python 2 (say scriptA) from within another script(scriptB) using the subprocess.Popen functionality in python 3

The script that I wish to call implements an argparse method which expects two arguments something like below: ScriptA (needs python 2):

def get_argument_parser():
'''
'''
import argparse

parser = argparse.ArgumentParser("Get the args") 

parser.add_argument("-arg1", "--arg1",required = True,
                    help = "First Argument")

parser.add_argument("-arg2", "--arg2",required = True,
                    help = "Second Argument")

return parser

Now, I am calling the above script using subprocess as follows: ScriptB:

value1 = "Some value"
value2 = "Some other value"
subprocess.Popen(["C:\\Python27\\python.exe ", ScriptAPATH, " -arg1 " , value1, " -arg2 ", value2],shell = True, stdout = subprocess.PIPE)

However, I am getting an error that: error: argument -arg1/--arg1 is required

What I tried next is to replace subprocess.Popen with os.system something like below:

cmd = "C:\\Python27\\python.exe scriptA.py" + " -arg1 " + value1 + " -arg2 " + value2
os.system(cmd)

This works fins and I am able to access the arguments from ScriptA in this case. Any pointers as to what could be going wrong in the first case? I am kind of new to python so any sort of help would be appreciated

Upvotes: 5

Views: 6266

Answers (2)

yash_maheshwari
yash_maheshwari

Reputation: 1

You can call a python script from another script using subprocess library...

import subprocess

new_price=550
old_price=400

p = subprocess.call(
    ['python.exe','missing_prices.py','--new_prices',new_price,'-- 
     old_prices',old_price,],)

In this way you can do this, i am passing this argument to argparse.

Upvotes: 0

jfs
jfs

Reputation: 414149

Either pass the command as a string exactly as you see it on the command-line or if you use a list then drop space characters around arguments:

from subprocess import check_output

output = check_output([r"C:\Python27\python.exe", script_path,
                       "-arg1" , value1, "-arg2", value2])

If you leave spaces; they are wrapped with double quotes. print sys.argv in the script, to see exactly what arguments it gets.

Upvotes: 4

Related Questions