ElectronJS does not properly create App using npm python-shell - python

I try to create simple App using ElectronJS and engine in it - simple python code (Simple Calculator.) In Dev process everything is ok - Project is working as I expect, but when I packaging it in App - python code do not response
code on gitLab : https://gitlab.com/olegvpc/python-electronjs-calc
Can somebody help me? :-(. PLEASE
calk.py
from sys import argv
from calculator.simple import SimpleCalculator
def calc(text):
try:
c = SimpleCalculator()
c.run(text)
# print(c.log)
return c.log[-1].split(" ")[-1]
except Exception as e:
print(e)
return 0.0
if __name__ == '__main__':
print(calc(argv[1]))
path of main.js
......
ipcMain.on('python:request', (e, input) => {
sendToPython(input);
});
function sendToPython(input) {
console.log(input)
var { PythonShell } = require('python-shell');
let options = {
mode: 'text',
args: [input]
};
PythonShell.run('./py/calc.py', options)
.then((messages)=> {
console.log(messages)
mainWindow.webContents.send("python:result", messages)
})
.catch((err) => console.log(err))
}
.......
file renderer.js
let input = document.querySelector('#input')
let result = document.querySelector('#result')
let btn = document.querySelector('#btn')
function handleClick() {
// console.log(input.value)
ipcRenderer.send('python:request', input.value)
}
ipcRenderer.on('python:result', (data) => {
result.textContent = data
input.value = ""
})
btn.addEventListener('click', () => {
handleClick();
});

Related

When calling JS function from Python: execjs._exceptions.ProgramError: Error: Cannot find module 'serialport'

I am attempting to call a function from a .js file in my python script using Pyexecjs.
with open("simulations/simulator.js", "r") as f:
js_code = f.read()
ctx = execjs.compile(js_code)
result = ctx.call("function")
result
But when calling the function, I get this error:
execjs._exceptions.ProgramError: Error: Cannot find module
'serialport'
The JS function that I am calling looks like this:
process.title = Simulator | ${process.argv[3]} | ${process.argv[4]}
var SerialPort = require('serialport')
const xps = new SerialPort(process.argv[3], {
baudRate: 115200,
}, (err) => {
if (err) console.error(`ERROR ${err}`)
})
xps.asyncWrite = function (data) {
return new Promise((resolve, reject) => {
this.write(data, (err, results) => {
if (err) {
reject(err)
} else {
resolve(results)
}
})
})
}
const UrinalFlush = async () => {
//console.debug(' User with Flush', '\n','User Detected (wait 5 sec.)')
await xps.asyncWrite(IR1)
await delay(6000)
await xps.asyncWrite(IR0)
console.debug(' User departing... Flush starting')
await delay(5000)
console.debug(' Flush Completed')
Start()
}
I have run npm install serialport successfully but, I still am not sure what needs to be done next. Could someone point me in the right direction?

How to solve "Socket error: [Errno 110] Connection timed out" in Chaquopy Android-kotlin

Recently I've been working on Chaquopy, Android-Python Library and my aim is to build a Port Scanner in android.
Code for Port Scanner Activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import com.chaquo.python.PyObject
import com.chaquo.python.Python
import com.chaquo.python.android.AndroidPlatform
import com.example.happlication.R
import com.example.happlication.adapter.servicesAdapter
import com.example.happlication.databinding.ActivityPortScannerBinding
import com.example.happlication.servicesModel
import java.util.*
class PortScannerActivity : AppCompatActivity()
{
lateinit var binding: ActivityPortScannerBinding
lateinit var activity: Activity
lateinit var scanoutput: PyObject
lateinit var pyObj: PyObject
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_port_scanner)
binding = DataBindingUtil.setContentView(this, R.layout.activity_port_scanner)
initView()
onClick()
}
private fun initView()
{
activity = this
window.statusBarColor = this.resources.getColor(R.color.black)
}
private fun onClick()
{
binding.ivBackArrow.setOnClickListener {
finish()
}
binding.btnSearch.setOnClickListener {
if (binding.edtIpaddress.text.toString().isNotEmpty())
{
if (binding.edtPortnumber.text.toString().isNotEmpty())
{
callScanner(this).execute()
binding.btnSearch.hideKeyboard()
}
else
{
Toast.makeText(activity, "Enter the port number", Toast.LENGTH_SHORT).show()
}
}
else
{
Toast.makeText(activity, "Enter the IP address", Toast.LENGTH_SHORT).show()
}
}
}
inner class callScanner(private var activity: PortScannerActivity?) : AsyncTask<String, String, String>()
{
override fun onPreExecute()
{
super.onPreExecute()
binding.loading.visibility = View.VISIBLE
}
var result=""
var error=""
override fun doInBackground(vararg p0: String?): String
{
try
{
if (! Python.isStarted()) {
Python.start(AndroidPlatform(this#PortScannerActivity))
}
var ipaddress=binding.edtIpaddress.text.toString()
var portnumber=binding.edtPortnumber.text.toString()
var py=Python.getInstance()
pyObj = py.getModule("portscanning")
scanoutput=pyObj.callAttr("portScanner",ipaddress, portnumber.toInt())
result=scanoutput.toString()
return result
}
catch (e: Exception)
{
error=e.toString()
}
return "false"
}
override fun onPostExecute(result: String?)
{
super.onPostExecute(result)
binding.loading.visibility = View.GONE
if (error.isNotEmpty())
{
binding.llErrorsection.visibility=View.VISIBLE
binding.tvError.visibility=View.VISIBLE
binding.tvError.text=error.toString()
}
else if (result.toString().isNotEmpty())
{
binding.llDetails.visibility=View.VISIBLE
binding.tvOuput.visibility=View.VISIBLE
binding.tvFinalOutput.visibility=View.VISIBLE
binding.tvFinalOutput.text=result.toString()
}
}
}
fun View.hideKeyboard() {
val inputManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(windowToken, 0)
}
}
Python file: portscanning.py
# importing the sockets module
import socket
def portScanner(target, port):
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
t_ip=socket.gethostbyname(target)
print(f"starting scan on host {t_ip} with portnumber {port}")
try:
s.connect((t_ip, port))
a=(f"port {port} is open")
return a
except Exception as e:
b=(f"port {port} is closed")
print(e)
return b
The Error I got:
Now if I run this Python file in normal windows-python interpreter then everything works fine
So is there some kind of permission I need to provide to this application, just like internet
OR some thing like that ??
OR is it having some other solution, Please let me know
Thanks for your answers!!

Python Hug REST API consumed in .NET, JSON looks weird

When consuming a Hug REST endpoint from .net JSON has embedded characters. A complete failing example posted below. Any help greatly appreciated.
Python
#hug.post('/test')
def test(response, body=None):
input = body.get('input')
print('INSIDE TEST ' + input)
if input:
dict = {"lastname":"Jordan"}
dict["firstname"] = input
return json.dumps(dict, sort_keys=True, default=str)
.NET (can only use .net 3.5)
private static object GetParsedData(string data)
{
var posturl = "http://localhost:8000/test";
try
{
using (var client = new WebClient())
{
// upload values is the POST verb
var values = new NameValueCollection()
{
{ "input", data },
};
var response = client.UploadValues(posturl, values);
var responseString = Encoding.UTF8.GetString(response);
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
JObject rss = JObject.Parse(responseString);
Console.WriteLine((string)rss["lastname"]);
}
}
catch (WebException ex)
{
if (ex.Response is HttpWebResponse)
{
var code = ((HttpWebResponse)ex.Response).StatusCode;
var desc = ((HttpWebResponse)ex.Response).StatusDescription;
}
//_logger.Error(ex.Message);
}
return false;
}
responseString looks like this:
"\"{\\\"firstname\\\": \\\"Mike\\\", \\\"lastname\\\": \\\"Jordan\\\"}\""
JObject.Parse throws error:
Newtonsoft.Json.JsonReaderException:
'Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 53.
Workaround - If I do something horrible like this to responseString JObject parses correctly:
str = str.Replace("\\", "");
str = str.Substring(1, len - 2);
Whats going on?
The default hug output format is json; it is not necessary to call json.dumps on return values, hug will do this automatically.

Alamofire HTTP request with Python backend

I have been stuck on this thing for a very long time, and I need help from you guys.
Try to use Alamofire to upload POST a picture to the back end, so that I can use that picture to get some result from my server.
my front code is
import UIKit
import Alamofire
class ViewController:UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate
{
#IBOutlet weak var myImageView: UIImageView!
#IBAction func uploadButtonTapped(sender: AnyObject) {
myImageUploadRequest()
}
#IBAction func selectPhotoButtonTapped(sender: AnyObject) {
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(myPickerController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
myImageView.image = info[UIImagePickerControllerOriginalImage] as?
UIImage
self.dismiss(animated: true, completion: nil)
}
func myImageUploadRequest()
{
// convert image to data object
guard let imageData = UIImageJPEGRepresentation(myImageView.image!, 1) else {
print("Could not get JPEG representation of UIImage")
return
}
// send multipart request
Alamofire.upload( multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: "imagefile", fileName: "image.jpg", mimeType: "image/jpeg")},
to: "http://123123123123/image",
encodingCompletion: { encodingResult in
// check the response
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
// Show progress
}
upload.responseJSON { response in
// Handle response
}
case .failure(let encodingError):
print(encodingError)
// Handle Error
}
})
}
}
My back end is
#app.route("/image", methods=["GET", "POST"])
def image():
if(request.method == 'GET'):
return '{ Success }'
file = request.files['file']
img = Image.open(request.files['file'])
img.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
return classify_image.pic_tensorflow('/templates/images/file.jpg')
So, I have been getting this error in the console for now:
zechengpart[55172:9628252] [MC] Reading from private effective user
settings. 2018-03-13 02:50:01.108562-0500 zechengpart[55172:9628293]
[discovery] errors encountered while discovering extensions: Error
Domain=PlugInKit Code=13 "query cancelled"
UserInfo={NSLocalizedDescription=query cancelled}
And I already fixed the infoplist issue about http not https.
When I ping the server, it gives me
123.123.123.123 - - [13/Mar/2018 02:50:05] "POST /image HTTP/1.1" 400 -
How can I debug here to avoid that error info?
Please help, I am struggle with this for too long time.

In AngualrJS using $http, how to get the value of a variable set in Python CGI?

I'm making a POST request from AngularJS to Python.
I started with an JavaScript example. It works properly returning all the values.
However, when I try to do it from AngularJS I'm not able to read the value of the variable posted.
JAVASCRIP EXAMPLE THAT WORKS PROPERLY (I'm able to get the value (Mike) back of Name):
JS code
<script language="Javascript">
function asyncChange()
{
var request;
if (window.XMLHttpRequest) {
request = new window.XMLHttpRequest();
} else {
// Versiones antiguas de Internet Explorer.
request = new window.ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST","nctest.py" , true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("Name=Mike");
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
document.getElementById("myLabel").innerHTML = "Hello " + request.responseText + "!";
}
}
}
</script>
nctest.py
#!/usr/bin/python
import cgi
input = cgi.FieldStorage()
print "Content-type: text/html\n\n"
print "input[Pe].value: "
print input["Pe"].value
ANGULARJS DOESN'T WORK PROPERLY (I'm not able to get the value (Mike) back of Name):
Angularjs code:
(function(){
'use strict'
var sectest= {
controller:sectestCtrl,
templateUrl:'app/components/component_test/test.html',
}
angular
.module('myapp')
.component('secTest',sectest);
function sectestCtrl($http){
var prac= this;
prac.method = 'POST';
prac.url = 'nctest.py';
prac.data = {Name : 'Mike'};
prac.data_answer
prac.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
prac.sendHTML = send;
function send(){
prac.code = null;
prac.response = null;
$http({method: prac.method, headers: prac.headers, url: prac.url, data: $.param(prac.data)}).
then(function(response) {
prac.status = response.status;
prac.data_answer = response.data;
console.log("OK prac.data_answer: ", prac.data_answer)
}, function(response) {
prac.data_answer = response.data || 'Request failed';
prac.status = response.status;
});
};
}
})();
nctest.py code
#!/usr/bin/python
import json
import cgi
input = cgi.FieldStorage()
print "Content-type: text/html\n\n"
print input["Name"].value
The problem is that prac.data_answer prints blank value.
I have already try with different headers for both angularjs and python codes but none seems to work:
prac.headers = { 'Content-Type': 'application/json' };
prac.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
prac.headers = { 'Content-Type': 'text/html\n\n' };
Many thanks.
There are 2 separate issues you're trying to address. Server (CGI) & client(angularjs). First check to see that you are receiving the data over the network - using Chrome developer tools, under the Network tab. If so, there's no need to change the Content-Type to json, since angular by default assumes all http data is in json format.
I don't think you need all those attributes for a post request. Seems like an overkiller when it can be simpler. Try this:
$http.post(url, data).then(function(response){
console.log(response.data);
});

Categories