问题
I have a Electron project which executes some python script using NodeJS's child_process module. My python script is in the root folder of my project.
Here's how I call the python script:
let py = spawn('python',['ResolvePosition.py', obsFilePath, navFilePath])
py.stdout.on('data', data => console.log('data : ', data.toString()))
py.on('close', ()=>{
// Python ends, do stuff
})
This works fine if I run my electron app with npm start
When I build an executable for Windows using the npm module electron-builder
and run the executable from dist/win-unpacked/my-app.exe
, this won't work, it seems that my script is not accesible with python ./my-script-py
.
So, how can I make this code works for the built project?
回答1:
You can include the script in extraResources:
"build": {
"extraResources": "python_scripts",
...
And then the dir will be at the app root:
let python = spawn('python', [path.join(app.getAppPath(), '..', 'python_scripts/my_script.py'])
回答2:
I've solved my problem. I'll explain for possible future readers with the same problem.
Using electron builder, there are some options possible for not to package the application source code into an electron file. These options are:
asar
Whether to package the application’s source code into an archive, using Electron’s archive format. Defaults to true. Node modules, that must be unpacked, will be detected automatically, you don’t need to explicitly set asarUnpack - please file issue if this doesn’t work.
Or you can pass object of asar options.
asarUnpack
A glob patterns relative to the app directory, which specifies which files to unpack when creating the asar archive.
DOCS
Setting asar
to false
solves the issue, but it is not recommended by electron-builder
.
So including all the files I need to unpack in a folder, and using
"asarUnpack" : "my-folder/*"
is the right way. Now all the files unpacked are available in /resources/app.asar.unpacked/my-folder
Another thing to take into account is that using the path './ResolvePosition.py'
is going to look at the root folder of my electron project, not the path where my NodeJS file is located, I need to use :
let python = spawn('python', [path.join(__dirname, '../app.asar.unpacked/my-folder', 'ResolvePosition.py'), obsFilePath, navFilePath])
来源:https://stackoverflow.com/questions/41199981/run-python-script-in-electron-app