Search code examples
pythonnamespacespython-multithreadingargparse

how to use positional argument from argparse.Namespace


I am trying to build a cli and wxpython gui application in two files. The wx app calls the cli app for functionalites. When I wrap my arguments in the wx app to a Namespace it does not get accepted from the cli app. window.py: error: the following arguments are required: filepath

I simplified the files to show only the related parts:

window.py

import os
from argparse import Namespace
from threading import Thread
from main import main

def window():
    try:
        print('window try')
        args = Namespace(
                        filepath = os.getcwd()+'file.xy',
                        outputpath =  os.getcwd()
                        )
        thread = Thread(target=main, args=(args,))
        thread.start()
        thread.join()
    except Exception as e:
        print(f'error:{e}')

if __name__ == '__main__':
     window()

main.py

import os
import argparse


def main(*args):
    print(f'START main args:{args}, type of args:{type(args)}')
    if args:
        args=args[0]
    print(f'tuple0:{args}, type of args:{type(args)}')
    parser = argparse.ArgumentParser()
    parser.add_argument('filepath', default=os.getcwd())
    parser.add_argument('-o', dest='outputpath')
    args = parser.parse_args()
    print(f'DONE main args:{args}, type of args:{type(args)}')

if __name__ == '__main__':
    main()

output:

➜  argparse python3 main.py ~/Documents/
START main args:(), type of args:<class 'tuple'>
tuple0:(), type of args:<class 'tuple'>
DONE main args:Namespace(filepath='/Users/novski/Documents/', outputpath=None), type of args:<class 'argparse.Namespace'>
➜  argparse python3 window.py      
window try
START main args:(Namespace(filepath='/Users/novski/Documents/argparse/file.xy', outputpath='/Users/novski/Documents/argparse'),), type of args:<class 'tuple'>
tuple0:Namespace(filepath='/Users/novski/Documents/argparse/file.xy', outputpath='/Users/novski/Documents/argparse'), type of args:<class 'argparse.Namespace'>
usage: window.py [-h] [-o OUTPUTPATH] filepath
window.py: error: the following arguments are required: filepath

Why does Namespace(filepath... doesn't get accepted as filepath when i hand it over through args from my window.py to main.py?

Is there a better solution, how to use my cli app (main.py) from the GUI (window.py)?


Solution

  • How about running the parser conditionally?

    if args:
        args=args[0]
        print(f'tuple0:{args}, type of args:{type(args)}')
    else:
        parser = argparse.ArgumentParser()
        parser.add_argument('filepath', default=os.getcwd())
        parser.add_argument('-o', dest='outputpath')
        args = parser.parse_args()