Search Posts

Visits: 99

macOS CatalinaでVS Codeを使用してPython開発

GitHub環境のサブディレクトリを追加したワークスペースを新規作成。GitHub環境の下のディレクトリで開発していたが、VS Codeの解釈するディレクトリ構造とPythonの認識する相対パスがずれているので、Python開発用のワークスペースを新規に定義した。
デバッグ環境は、標準提供されているものを使用した。
コマンドラインで実行するプログラムをデバッグする際に、 .vscode/launch.jsonに”args”の指定を追加した。
デバッグについては、VS Code Debugging及びVS Code launch configurations参照

{
  // IntelliSense を使用して利用可能な属性を学べます。
  // 既存の属性の説明をホバーして表示します。
  // 詳細情報は次を確認してください: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Current File",
      "type": "python",
      "request": "launch",
      "program": "${file}",
      "console": "integratedTerminal",
      "args": ["data/in/ubl-tc434-example8.xml", "data/out/ubl-tc434-example8.tsv"] // invoice2tsv
      // "args": ["data/out/ubl-tc434-example6.tsv", "data/out/ubl-tc434-example6.xml"] // genInvoice
    }
  ]
}

この指定で、[実行]メニューからコマンドラインで引数を指定したデバッグが可能となった。

引数から入出力のファイルパスを取得する

file_path関数を定義してファイルパスを取得して、os.path.isfile()で入力ファイルの存在チェックしている。ファイルがなければ、 sys.exit()で処理を中断。

  # Create the parser
import sys 
import os
import argparse

def file_path(pathname):
  if "/" == pathname[0:1]:
    return pathname
  else:
    dir = os.path.dirname(__file__)
    new_path = os.path.join(dir, pathname)
    return new_path

my_parser = argparse.ArgumentParser(prog='genInvoice',
                                      usage='%(prog)s [options] infile outfile',
                                      description='ファイル変換')
  # Add the arguments
  my_parser.add_argument('inFile',
                        metavar='infile',
                        type=str,
                        help='入力ファイル')
  my_parser.add_argument('outFile',
                        metavar='outfile',
                        type=str,
                        help='出力ファイル')

  args = my_parser.parse_args()
  in_file = file_path(args.inFile)
  out_file = file_path(args.outFile)
  # Check if infile exists
  if not os.path.isfile(in_file):
      print('入力ファイルがありません')
      sys.exit()