【问题标题】:subprocess call with argparse使用 argparse 调用子进程
【发布时间】:2018-09-17 21:35:59
【问题描述】:

文件夹目录结构如下:

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

a.py 看起来像...

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 尝试导入并运行 b,而 b 需要 argparse。

如果我只是从终端运行 b.py,运行 b 的命令将是

python b.py -v subsubfolder_testvideos/a.avi

我正在尝试运行 a.py 并让 b.py 在其中运行。

在 a.py 文件中,我编写了如下代码。

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)

并且输出错误是 FileNotFoundError: [Errno 2] No such file or directory: '/subfolder_AA/': '/subfolder_AA/'

此错误是否来自我使用 subprocess.call 的错误命令?我该如何解决这个问题?

【问题讨论】:

    标签: python directory subprocess argparse


    【解决方案1】:

    首先,当您为文件夹添加前缀 / 时,您正在执行绝对文件路径。

    其次,您应该使用常规的 python 导入而不是子进程调用。您应该在子文件夹中放置一个__init__.py 以便能够从中导入。然后您可以修改b.py,以便将ArgumentParser 中的参数传递给另一个函数,然后由a.py 导入。比如:

    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')
    

    【讨论】:

    • 谢谢!如果b是在同一个目录下导入c.py,是否需要修改'import c'这一行?
    • 哦,我想通了! '将 subfolder_AA.b 作为 ots 和 ots.run("testvideos/1.avi") 导入!!
    猜你喜欢
    • 2011-06-30
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 2018-01-04
    相关资源
    最近更新 更多