2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-09-18

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を使う場合混同してしまいそうなのでよくないかも。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?