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

ElectronからPythonシェルを実行する際に、複数引数を渡してPythonを実行する。

はじめに

ネットで調べると文字列1つを送るサンプルコードは多く出るが、複数パラメータを渡すサンプルコードが見つからなかったのでまとめた。

概要

ElectrionからPythonを実行する際に、複数のパラメータを渡す際の方法を記載する。
ElectronではPythonShellでPythonを実行し、Python側ではargparseライブラリで実行引数を取得する。

Electron側のサンプルコード

PythonShellをインポートして実行する。optionsのargsに引数を並べるのがポイント。

ElectronApp.js
const {PythonShell} = require('python-shell');

const pyMain = '/path/to/pyMain.py';
let options = {
  mode: 'text',
  pythonOption: ['-u'],
  args:[
    '-param1', 'name1',
    '-param2', 'name2' 
  ]
}
let pyshell = new PythonShell(pyMain, options);

pyshell.send();
pyshell.on('message', function(data){
  console.log(data);
});

Python側のサンプルコード

pyMain.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-param1", help="parameter1 discription")
parser.add_argument("-param2", help="parameter2 discription")
args = parser.parse_args()
print(args.param1) # name1
print(args.param2) # name2
Why not register and get more from Qiita?
  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
No 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
ユーザーは見つかりませんでした