PYTHON module "requests" not working with packaged electron app - javascript

In my electron app I have a python file that has two import statements shown below
import requests
import shutil
The app works fine without an errors in the IDE but after packaging the electron app with
npx electron-packager ./ --platform=darwin --icon=src/img/logo.icns
The app gives me this error
It only gives this error for the 'requests' module but not the 'shutil' module. And yes, 'requests' is installed on my computer. I also use the PythonShell module in the js file to run the python file like below
function version_checker(){
form.classList.toggle('hide');
circle.classList.toggle('show');
let pyshell = new PythonShell(__dirname + '/version_checker.py');
pyshell.on('message', function (message){
console.log(message);
if(message !== "same"){
console.log("updating")
}
else{
if(message !== "restart"){
form.classList.toggle('hide');
circle.classList.toggle('show');
}
else{}
}
})
pyshell.end(function (err,code,signal) {
if (err) throw err;
console.log('The exit code was: ' + code);
console.log('The exit signal was: ' + signal);
console.log('finished');
});
}
I also do not wish to compile the python file into an executable because the python script "talks" to the js file. I am also on a M1 Pro Macbook running macOS Ventrua if that helps
How do I package the app and include the 'requests' module OR How do I make the 'requests' module work with the packaged app
I did find a stackoverflow post that asked a similar question but the owner voluntary took down the question so I wasn't able to view it
I looked at this post but it wasn't helpful because I'm not using 'anaconda' or 'child-process'

PythonShell just calls the system's Python interpreter, so use PIP to install the requests library
Or specify the interpreter as follows:
new PythonShell(__dirname + '/version_checker.py', {
pythonPath: '/path/to/python'
})
Note: For production purposes, it is recommended to include an interpreter in electron and install dependencies
It seems you just want to make a HTTP request, why not try fetch in javascript?

If the error is ModuleNotFoundError, then your python interpreter is struggling to find the requests module. This can happen for a number of reasons:
Module does not exist: We can rule this out if your ide ran program successfully.
2: Module is not where interpreter expects to find it: Most likely.
Almost certainly the python interpreter used by your IDE is different to the one you ran after packaging the electron app.
The solution is to either:
a. make sure the location of requests is visible to the PYTHONPATH by setting that in the proper location (I don't use MAC but I believe you have ~/.bash_profile file to set it in or
b. Explicitly add the request module location via a sys.path.append command in your code eg
import sys
import os
path = 'your path to request module'
sys.path.append(os.path.join(path, 'requests')
import requests
You should be able to find the path location by investigating your IDE and looking where you set the module to be included in your program

Related

I want to call Python in Node.js and use SymPy module

I use Node.js and Express as server side language.
And I made a website using AWS.
I need to use Python because I need complicated calculations.
However, I don't know how to call Python from Node.js.
Please tell me how to use Python's SymPy module in Node.js.
In case you need to call a external script from your Node.js application, you can always spawn a process to do so.
There is (obviously) a npm module to make it easier for you to use a python script from Node.js. You can use python-shell module to launch your "complicated calculation" scrip if you're not able to find the equivalent in Node.js ecosystem.
Here a basic example inspired by the SymPy & python-shell documentation:
script.py
from sympy import *
x = Symbol('x')
print (limit(sin(x)/x, x, 0))
app.js
const {PythonShell} = require('python-shell');
PythonShell.run('script.py', null, function (err, res) {
if (err) throw err;
console.log(res[0]); // 1
});
Also pay attention to have the SymPy module in your path.

How to import strophe using requirejs?

I'm trying to use strophe.js with relay-starter-kit. I checked out relay-starter-kit, added "strophe": "^1.2.2" to package.json and ran npm install.
I can't find how to import strophe without getting errors. If I just try import Strophe from 'strophe'; I get errors that webpack can't resolve strophe-polyfill. I added a resolve alias for that pointing to the main strophe.js file, but that hasn't helped (I just get a console message Uncaught ReferenceError: Strophe is not defined).
It looks like strophe has some weird module system (it mentions AMD in github but I thought that meant I could just require it, but apparently not). All the examples I've seen import it in an HTML file and clutter the global namespace. I need to use it from within react so I don't think that will work.
How can I import strophe to use in my es6 files?
Since I wasted hours of my life on this, here's the answer:
Include strophe in the HTML file with:
Edit server.js to make webpack expose strophe as a static path with:
app.use('/node_modules/strophe', express.static('node_modules/strophe'));
In the react component, there's no need to import strophe since it's now globally available. Instead just connect with, e.g.:
var connection = new Strophe.Connection("ws://" + server + ":5280/websocket/");
try to use import * as XMPP from strophe.js then call
var connection = new XMPP.Strophe.Connection(BOSH_SERVICE) to connect server

require is not defined? Node.js [duplicate]

This question already has answers here:
Client on Node.js: Uncaught ReferenceError: require is not defined
(11 answers)
Closed 5 months ago.
Just started working with Node.js. In my app/js file, I am doing something like this:
app.js
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Am I really running a server?!');
}).listen(8080, '127.0.0.1');
console.log('running server!');
When I'm in my terminal and run node app.js, the console spits out 'running server!', but in my browser I get, Uncaught ReferenceError: require is not defined.
Can someone explain to me why in the terminal, it works correctly but in the browser, it doesn't?
I am using the node's http-server to serve my page.
This can now also happen in Node.js as of version 14.
It happens when you declare your package type as module in your package.json. If you do this, certain CommonJS variables can't be used, including require.
To fix this, remove "type": "module" from your package.json and make sure you don't have any files ending with .mjs.
In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.
node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().
require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().
There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).
But, you won't be running a web server in your browser as that is not something the browser has the capability to do.
You may be interested in browserify which lets you use node-style modules in a browser using require() statements.
As Abel said, ES Modules in Node >= 14 no longer have require by default.
If you want to add it, put this code at the top of your file:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
Source: https://nodejs.org/api/modules.html#modules_module_createrequire_filename
Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require(), do not work in the browser.
See browserify or webpack if you wish to serve browser-specific modules from Node.
Just remove "type":"module" from your package.json.
I solve this by doing this steps:-
step 1: create addRequire.js file at the project root.
step 2: inside addRequire.js add this lines of code
import { createRequire } from "module";
const require = createRequire(import.meta.url);
global.require = require; //this will make require at the global scobe and treat it like the original require
step 3: I imported the file at the app.js file head
import "./start/addRequire.js";
now you have require beside import across the whole project and you can use both anywhere.
Point 1: Add require() function calling line of code only in the app.js file or main.js file.
Point 2: Make sure the required package is installed by checking the pacakage.json file. If not updated, run "npm i".
My mistake: I installed ESLint to my project and made a mistake when I filled out the questionnaire and chose wrong type of modules)
Maybe it will be helpful for someone))
What type of modules does your project use? ยท * commonjs
I solve it, by removing below line from package.json file
"type": "module"
Hope it will solve the problem.

Problems concerning require() javascript

I'm trying to run the JavaScript client for the Tumblr API but I'm getting a "require not defined" error. I've scoured almost every corner of SO trying to find a way to make it work.
I've managed to use Browserify to recognize it but at some point, I'm getting a fs.readFileSync error.
Then I tried RequireJS and again it does the require thing but I'm getting a Module name "something" has not been loaded yet for context"
I'm really new to Node.js but if I'm understanding it correctly the require() part isn't something the browser can do right? Can anyone guide me as to what solutions I can take for this? If it helps, I'm not planning to upload this on a server or anything. I'm just trying to run it on my local computer and just planning to run the API locally.
Edit:
Here's what I have on my main.js
var tumblr = require('index.js');
var client = tumblr.createClient({
consumer_key: '<consumer key>',
consumer_secret: '<consumer secret>',
token: '<token>',
token_secret: '<token secret>'
});
// Show user's blog names
client.userInfo(function (err, data) {
data.user.blogs.forEach(function (blog) {
alert('dang');
});
});
When I try requirejs, I do this to reference it <script data-main="script/main" src="scripts/require.js"></script>
It seems to me that you might be confusing server-side JavaScript (Node) and client-side JavaScript (in the browser). The Tumblr API you're trying to use is for Node only; you can't run it in a browser. You have to:
Install NodeJS and NPM on your system
npm install tumblr.js
Run the script with node <script name>
Start with the Tumblr.js example script, then customize for your own purposes!

Is there a way to import strings from a text file in javascript, meteor?

I have a programm where I need to have long multi line strings. It's a pain to store them in the .js document, because js doesn't have multi line strings and I end up having a twice as long as the screen width line looking as ugly as "This is an example.\n"
Is there a way to have a txt file, from where I can import strings with new lines (or at least just import strings)?
There is a Meteor Assets object that allows you to read files in the private directory of your app, in the following way for example for text files.
Assets.getText("foo.txt", function (err, res) { ... });
See full documentation: http://docs.meteor.com/#assets
Previous answer works only for public files. If you want to access file data that is visible only on the server you should probably use 'fs' npm module. It's described in details here: http://www.eventedmind.com/posts/meteor-file-uploader-part-2-server-side-save
The meteor-yaml package makes this easy - it automatically loads any .yaml files in your project, parses them into JavaScript objects, and makes them available in YAML.data.
In my application I have some code outside of the meteor app that needs the same settings, so I prefer to have the config file outside of the meteor project directory. Then I load the file like this:
var fs = Npm.require('fs');
fs.readFile('<path to file>.yaml', 'utf8', function(err, data) {
if(err) {
//Throw exception if the file is missing
throw new Error("Missing config file")
}
else {
//Read the file into a JavaScript object
config = YAML.parse(data);
}
});
Unfortunately, the meteor-yaml package is a little out of date with how the meteor team wants node packages to be loaded now, so if you're using a recent version of meteor the package won't work out of the box.
I filed a bug about this, but in the meantime to get around it I installed it as a private package, as opposed to installing it from atmosphere, and fixed the bug. To do this:
Clone the repo under your projects packages/ directory
Comment out the Npm.require lines.
Add a call to depends:
Npm.depends({yamljs: "0.1.4"});
Run meteor. Meteor will detect the meteor-yaml private package and install the dependencies.

Categories

Resources