I have an application where the output is written into a file (.py) by using javascript.
I'm using this application to write python script into the file. Now I want to run the python script automatically on cmd(Windows) right after the output was written.
Is there a way to do so ? Is it possible without using "NodeJS"
So apparently everything happens with a single click on the application.
Thanks.
Node js provides the child process module,
which you can use to basically spawn a child process from your js application.
since you have not shared any source code so i am not sure what your specific use case is but a basic way of spawning python script would be like this.
import { spawn } from 'child_process';
let scriptPath = './script.py' // path to your python script
var script = spawn('python', ['-u', scriptPath, arg1, arg2]); // arg1,arg2 can be any command line arguments required by your script or if not needed you can skip them.
script.stdout.on('data', data => {
console.log('Data: ', data.toString());
// implement your functionality here
});
you can similary bind on close and error events to your script and implement the functionality accordingly.
Why not storing your script in a script.py file? Why do you use .txt at all? With CMD and Python installed you should easily run .py scripts with a command line "python path/to/script.py", shouldn't you?
Edit: For checking out how to execute python on Node JS just use Google! Google is your friend! "execute python with node js" threw me this article: How to call python script from NodeJs
Related
I am writing an algo to analyze market data in Java, to visualize my data i'd like to make use of an existing charting library from tradingview. This free charting library runs on nodeJS.
I'm having a lot of trouble understanding how to populate it with my data resulting from my algorithm.
For example my Java code returns a "List< Candlestick >" object, how do i send this to the Javascript code running on the nodeJs ?
if someone would be so kind to give some global directions in how to approach this it would be very much appreciated.
My assumption here is that you have java code and the result you want to display is on nodejs.
While at this moment calling data from the API is suggested, also there is one more option we can use to solve your problem. This is a good case of polyglot programming. I have used graalvm.
Installation via sdkman
GraalVM
sdk install java 21.1.0.r11-grl
NodeJS
gu install nodejs
Both Main Projects are located here https://gitlab.com/graalvm-java-to-nodejs
Java Project (has method which return a list)
NodeJS Project(loads Java Class in NodeJS and call method on class reference to get the list)
Add any code to java library in my case I have a class which just return list of Point as given below:
public class GraphData {
public List<Point> getPoints() {
return List.of(new Point(1, 1), new Point(3, 5));
}
}
where Point is a POJO class to hold (x, y) value.
Clone this java project https://gitlab.com/graalvm-java-to-nodejs/graalvm-simple-java and execute ./gradlew clean build this should give you a executable jar which can be executed java -jar file.jar command.
Now, clone https://gitlab.com/graalvm-java-to-nodejs and install dependencies npm install then execute
node --jvm --vm.cp=/home/ashish/IdeaProjects/graavlvm/java-lib-gvm/build/libs/java-lib-gvm-1.0-SNAPSHOT.jar bin/www
Relevant code which interacts with java is as below:
var GraphDataJavaRef = Java.type('in.silentsudo.GraphData');
var graphData = new GraphDataJavaRef();
var data = graphData.getPoints();
in.silentsudo.GraphData class is loaded from the jar file which is provided to node program with argument named --jvm --vm.cp path/to/file.jar
Once you navigate to localhost:3000, you should see
Express Tutorial
Welcome to Express Tutorial
Response from Java class
[Point{x=1, y=1}, Point{x=3, y=5}]
I am trying to call a function in a python file from a js file, I got this to work through my console, but I am now trying to implement it in a mobile app using expo.
The way I had set this up is, I have the JS file for a certain screen in my app, this then calls a function in a separate JS file, which then calls the function in the python file.
I am using the child_process module to talk to python from JS.
And as I said, this was working before I tried to export the JS function to my screen file.
index.js
export function foo(process, sentence){
const spawn = require("child_process").spawn;
const process = spawn("python3", ["./python.py", sentence]);
...
}
screen.js
*other imports
import { foo } from "./filepath..."
...
But when I run npm start I get the following error:
Failed building JavaScript bundle.
While trying to resolve module `child_process` from file `/Users/mee/Documents/GitHub/project/app/screens/screen.js`, the package `/Users/mee/Documents/GitHub/project/node_modules/child_process/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/me/Documents/GitHub/project/node_modules/child_process/app/screens/screen.js`. Indeed, none of these files exist:
How can I fix this?
It won't work for few reasons
child_process is part of the node standard library, it's not available in other environments like react-native or browser
even if above was not true, there is no python3 executable on your phone
python.py file from your local directory wouldn't be even uploaded to the phone because bundler is only uploading one big js file with entire js code combined + assets, python.py is neither of those.
Only solution that make sense it to rewrite that code to javascript.
Technically it's not impossible, there might be a way to do that, by compiling python interpreter for mobile platform, or using some tool that translates python code into js, but it's not something that you should consider.
I was working on a Python script, and wanted to access Atom's current working directory in that script.
Atom is built on electron.js, and the way you do it in JavaScript is:
let filePath = atom.workspace.getActiveTextEditor().getPath();
I want this variable (simply the directory) in my Python script instead.
The idea of what you're trying to achieve is giving me some headaches. While it's certainly possible to invoke the Python interpreter from JavaScript, it's probably not the best user experience for people using your package.
Before even running the Python script, the package needs to check at least the following:
user has the correct version of Python installed
python is exposed to the PATH
the active file is eligible to be interpreted by Python
These are different problems, but nevertheless some you need to sort out.
You haven't specified, whether you invoke the Python script within a synchronous or asynchronous function. I'm going to assume the former since it's easier to follow for JavaScript beginners, but you might want to change that in a later step
JavaScript
// Import Node's spawn method
const { spawnSync } = require('child_process');
// Get path of active file
const activeEditorPath = atom.workspace.getActiveTextEditor().getPath();
// Spawn child process
const child = spawnSync('python', ['path/to/your/script', activeEditorPath]);
Python
import sys
# Get argument
active_editor_path = sys.argv[1]
# Print editor path
print(f'Active editor path: {active_editor_path}')
I have a frontend in HTML and JAVASCRIPT. I need to get value from nodejs file and display it in HTML label. So I create new node js file node.js as:
const Web3 = require('web3');
const web3 = new Web3('https://kovan.infura.io');
web3.eth.getBalance('0x9E632F36D8193a23ee76e7C14698aCF4b92869A2').then(console.log);
I include this file in script tag as:
<script src="node.js"></script>
First I want to look output in the console but it is giving an error
Uncaught ReferenceError: require is not defined
So, I try this code directly in HTML file within the script tag without including node file but still gives the same error.
Can somebody help me with this? I am new to use all this together.
Somehow, I managed to find a solution. I used browserify, which makes easy for me to run the nodejs code from my web app.
Browsers don't have the require method defined, but Node.js does. With Browserify you can write code that uses require in the same way that you would use it in Node.
browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single tag.
I referred this link: http://browserify.org/
I have webpage that needs to run some computation on start up. I want to keep this computation on the server side so the client cannot access the source code. I discovered pico, a module that is supposed to be "a bridge between server-side python and client side JavaScript".
I have a simply test.py:
import pico
def hello():
return "Hello World"
My JavaScript is also simple:
pico.load("../../../test.py");
pico.main = function() {
var displayMessage = function(message){
console.log("hello2");
console.log(message);
}
test.hello(displayMessage);
}
"../../../test.py" is the relative location of the python script to the pico folder
I then run "python -m pico.server" on the command line. When I go to my web page, open inspector, and go to the console I get the error: "Uncaught SyntaxError: Unexpected token i". 'i' is presumably from the first line import. Note that this same error happens if I don't run the pico.server command.
Any help would be great, as well as suggestions for alternative methods of doing this serverside vs clientside.
I may have an answer for you, however I have not been able to replicate the same error.
pico.load does not seem to work when file extensions are included in the argument, this is due to the function being designed to load sub-modules directly (i.e. module.sub_module) as in the pico API:
pico.load(module, [callback])
Load the Python module named module. The module will be available as a global >variable of the same name.
Submodules may be loaded by using dotted notation e.g. module.sub_module
To make sure I included ".py" file extension on the pico test page I have been working on and it failed to load the module, so this may be a problem if you are using the file extension.
Another possible issue was mentioned in a comment by holderweb. In the first pico example HTML the file client.js is included in an external <script> tag, this includes the functionality required to use pico. So you must have something similar to the following tag in your index.html head section:
<script type="text/javascript" src="/pico/client.js"></script>
For more insight I would be interested in seeing what/if the server logs at command line when the error occurs, and also the contents of your index.html page. Hope this helped!