SSS
SSS

Reputation: 671

subprocess call with argparse

The structure of folder directory is as follows:

folder_A
folder_A/a.py
folder_A/subfolder_AA/b.py
folder_A/subfolder_AA/subsubfolder_testvideos/a.avi

a.py looks like...

import cv2
import argparse as ap

def run(source=0, dispLoc=False):
    cam=cv2.VideoCapture(source)
    while True:
        ret, img = cam.read()
        if not ret:
            exit()
        if(cv2.waitKey(10)==ord('p')):
            break
        cv2.imshow("image",img)
    cv2.destroyWindow("image")

# Other scripts here....
if __name__ =="__main__":
    parser = ap.ArgumentParser()
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-d', "--deviceID", help="Device ID")
    group.add_argument('-v', "--videoFile", help="Path to Video File")
    parser.add_argument('-l', "--dispLoc", dest="dispLoc", 
    action="store_true")
    args = vars(parser.parse_args())

    if args["videoFile"]:
        source = args["videoFile"]
    else:
        source = int(args["deviceID"])

    run(source, args["dispLoc"])

a.py tries to import and run b, and b needs argparse.

If I simply run b.py from the terminal, the command of running b will be

python b.py -v subsubfolder_testvideos/a.avi

I am trying to run a.py and make b.py run inside it.

In the a.py file, I wrote the codes like below.

import sys
sys.path.append('~/Desktop/folder_A')
sys.path.append('~/Desktop/')
from os import system
import subprocess

subprocess.call(["python", "b.py","-v testvideos/a.avi"], cwd="/subfolder_AA/", shell=True)

and the output error is FileNotFoundError: [Errno 2] No such file or directory: '/subfolder_AA/': '/subfolder_AA/'

Is this error coming from my faulty command using subprocess.call? How could I fix this?

Upvotes: 0

Views: 1177

Answers (1)

mVChr
mVChr

Reputation: 50205

First, you're doing an absolute file path when you prefix the folder with /.

Second, you should use regular python imports instead of subprocess calls. You should put an __init__.py in the subfolder to be able to import from it. Then you can modify b.py so it passes the arguments from the ArgumentParser to another function that is then imported by a.py. Something like:

b.py:

def process_video(device_id=None, video_file=None):
    # ...do stuff...

if __name__ == '__main__':
    parser = ArgumentParser()
    # ...etc...
    return process_video(device_id=parser.deviceid, video_file=parser.videofile)

a.py:

from subfolder_AA.b import process_video

processed_video = process_video(video_file='testvideos/a.avi')

Upvotes: 2

Related Questions