0
1

More than 1 year has passed since last update.

pythonモジュールの関数をコマンドプロンプトで出力する

Last updated at Posted at 2023-03-06

(追記)この記事を読む前に

ありがたいことにコメントで自分で考えていたより良いやり方を教えていただいたので、以下を使ってください。@asobinin_kinsan さん、@shiracamusさんありがとうございました。

one_writner.py
python  -c "import os;print('\n'.join([x for x in dir(os) if x.islower() and '_' not in x]))"
d.py
import sys
import importlib


def main(module_name):
    module = importlib.import_module(module_name)
    for name in dir(module):
        if name[0] != '_':
            print(name, ':', type(getattr(module, name)).__name__)


if __name__ == '__main__':
    if len(sys.argv) == 2:
        main(sys.argv[1])
    else:
        print(f"Usage: {sys.argv[0]} MODULE_NAME")

(備忘のために残しますが、以下非推奨)はじめに

以下のような人にとって便利だと思います(私です)

  • 会社のWindows端末の縛りでjupyter notebookなどが使えない。
  • 標準モジュールで何ができるかぱっとわかりたい。公式ドキュメントに行くほどのことでもない。
  • dir()を叩くためにVScodeで開いているターミナルでpython3とわざわざ打って対話型に入っている。
  • VScodeがいい感じの表示をしてくれない。

コード

d.py
import argparse

def main():

    if args.os == True:
        import os
        d = dir(os)

    elif args.pandas == True:
        import pandas
        d = dir(pandas)

    else:
        d = []

    d_fil = [x for x in d if x.islower() and not '__' in x] 
    print(*d_fil, sep='\n')

if __name__ == '__main__':
    psr = argparse.ArgumentParser()
    psr.add_argument('-o', '--os', action='store_true')
    psr.add_argument('-p', '--pandas', action='store_true')
    args = psr.parse_args()

    main()


自分が見たかったのは関数だけなので他の内容はフィルターしています。
importの引数に変数は入れられないので、見たいモジュールが増えるたびにオプションとif文を変更する必要があるのは少し手間ですが自分用なのでOKということで。

0
1
7

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
0
1