Help us understand the problem. What is going on with this article?

Pythonでargparseをファイル間共有する

Usecase

複数のプログラムファイルに渡ってコマンドライン引数を共有したい

Method

ArgmentParserで作ったNamespaceオブジェクトをpickleでdump/loadする

Example

writer.pyでコマンドライン引数を受け取ってdump / reader.pyでload

$ python writer.py -i hope -p args.pkl 
Namespace(input='hoge', path='args.pkl') # print(args)
$ python reader.py 
hoge # print(args.input)
writer.py
import argparse
import pickle
from pathlib import Path

def get_args():
    parser = argparse.ArgumentParser(description='receive arguments')
    parser.add_argument('-i', '--input', required='True', help='input')
    parser.add_argument('-p', '--path', required='True', help='output path')

    return parser.parse_args()

def main():
    print(args)
    with open(args.path, mode='wb') as f:
        pickle.dump(args, f)

if __name__=='__main__':
    args = get_args()
    main()
reader.py
import pickle

def main():
    with open('args.pkl', mode='rb') as f:
        args = pickle.load(f)
    print(args.input)

if __name__=='__main__':
    args = get_args()
    main()

readerでもargparseを使う場合混同してしまいそうなのでよくないかも。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away