I am using Naked.toolshed.shell to execute javascript with python.
https://naked.readthedocs.io/toolshed_shell.html#javascript-node-js-execution-functions
The python code is like this.
def push_transaction(self, ...):
"""
node PushContractTransaction.js [...]
"""
arguments = [...]
)
response = muterun_js(self.current_dir + '/js/PushContractTransaction.js', arguments=arguments)
if response.exitcode == 0:
print(f"This is the response: {response}")
return
else:
raise PushContractTransactionException(response.stderr)
The javascript code that is called returns a string.
Now i want this string in python. I am getting this object as a reponse, but I don't know how to extract the return value from it.
Naked.toolshed.types.NakedObject object at 0x105a84390
I could log something to console and then use response.stderr but doesn't seem like a good solution and I think there is a much easier one.
Making it into an answer:
muterun_js returns a Naked object which has an stdout attribute for standard output stream data, a stderr attribute for standard error stream data, and an exitcode attribute for the exit code.
Getting output of javascript script:
naked_object = muterun_js('script.js')
print("Output", naked_object.stdout.decode("utf-8"))
Related
I am working on a project in which I am using node js and python together. My node js code makes a child process of python code. And I am sending some data from node js to python and also receiving some data back from python to node.
I call my python file like this.
const py = spawn('python', ['file.py', 'some_data']);
and for sending data back from python to node I am using print in python like this.
print("mydata")
and for receiving in nodejs I am using this code.
py.stdout.on('data', async (data) => {
//This data is python string as we can see above
var data_from_python = data.toString();
});
now the problem I am facing is string which come from python does not equal to node js string I have tried this.
data_from_python === "mydata" // false
and also this
data_from_python == "mydata" // false
both returns false.
But when I console the type of both using typeof operator it says string for both.
I want to know what is reason behind and what is the solution if we want to compare them or is there a better way to get data back from python to node. I know this "mydata" string is coming from buffer, python is putting it into the buffer and node is reading it from the buffer, and I think they both are different because one is python string and other is nodejs string, maybe it is because of under the hood both deal or make strings differently.
But what is the exact story behind if anyone one know please share your knowledge.
This is because print in python adds a new line after the data, So instead of getting mydata you will receive mydata\r\n. So you should check for the same in your condition, see below:
const { spawn } = require('child_process')
const py = spawn('python', ['py.py', 'some_data']);
py.stdout.on('data', async (data) => {
console.log(data);
var data_from_python = data.toString();
console.log(data_from_python == "mydata\r\n"); // outputs true
});
This question is NativeScript related.
I want to process the binary data after being read from file.
I followed the official doc here:
file-system#readingwriting-binary-data-fromto-a-file
with this, I can successfully read and write (in other word: "copy") the binary files. What I'm trying to accomplish now is to process the binary data ( it could be any sort of binary data, eg. image, database, etc... ) and then save it in file. But I can't figure out how to retrieve the raw binary data from a variable object returned by readSync, please have a look at the code below (btw currently testing on ios environment):
var source = sourceFile.readSync(e=> { error = e; });
console.log(typeof source.bytes);
console.log(typeof source.length);
console.log(source.bytes);
console.log(source.length);
When I execute this code, I see the these messages in console log:
CONSOLE LOG file:///app/views/login/login.js:99:12: object
CONSOLE LOG file:///app/views/login/login.js:100:12: number
CONSOLE LOG file:///app/views/login/login.js:101:12: <Pointer: 0x11da02000>
CONSOLE LOG file:///app/views/login/login.js:102:12: 1720728
From this output I surmise that source.bytes is a pointer object and not an array object... My question is: is there a way to store the data into array, possibily in Uint8Array type?
I finally found a solution to make it work on ios environment. It was written in the source code:
NativeScript: objc!Foundation.d.ts
So, use getBytes() to retrieve the data into array abject.
Example code:
var arr = new ArrayBuffer(source.length);
source.getBytes(arr);
var uint8arr = new Uint8Array(arr);
I am trying to list, in a select dropdown, some ontology elements using the following ajax:
$.ajax({
type: 'get',
url:"../py/ConfigOntology.py",
success: function(data){
$("#instance_image_1").append($("<option></option>").attr("value", data).text(data));
},});
"ConfigOntology.py" is a simple code that extracts and prints two ontology items. However, the ajax takes these two as a single string. Parts of this .py contents that generate the output are:
import rdflib, rdfextras, cgitb
from rdflib import Graph
cgitb.enable()
print ("Content-Type: text/plain;charset=utf-8")
print("")
def getImages(results):
for row in results:
print (row['storedImage'][50:])
sparql = "the query goes here"
results = ConfigOnto.query(sparql)
getImages(results)
I tried a php script with a php exec(), which gets the .py output as an array but the ajax also takes that a string. I tried JSON.parse(data) but got error saying "Uncaught SyntaxError: Unexpected token K in JSON at position 0" - referring to end of line in in .py output.
So, my "big" question is: how can I access the ConfigOntology.py output as individual items in the ajax() rather than a string, and what could be a possible fixed code for this problem.
P.S: this is my first ajax function so please go easy on me.
I think what you should do is to return a JSON Object in the endpoint of your ajax call.
If I understand it correctly right now you try to read the output of a python script in an ajax request which is not the normal workflow for this.
the normal workflow would be request (client, your browser) --> server(this is in your case the script, but it should really be a server) --> response (this can be a json Object or html, in your case it is just the console output.)
so what you need to do is to change your pyhton script that gives a console output into an endpoint of a server, and that endpoint should return a JSON response.
here is a simple example of json processing with Flask (a simple python webserver)
http://code.runnable.com/Up77jfzqtL5FAAAu/json-dumps-and-loads-in-flask-for-python
I hope this can get you started
I am making a website using Django and I want to pass a python object from my view (where it is created) through the Django template and to a Dajax call. The problem is that by the time it gets to dajax it has been turned into type unicode.
In my Template
<script>
var emailer = "{{emailer|safe}}"; <---If I omit the quotes here then I get a javascript error.
sessionStorage.setItem('emailer',emailer);
$(document).ready(function(){
$('.send').on('click', function(e){
var emailer = sessionStorage.getItem('emailer');
Dajaxice.InterfaceApp.sendEmail(submitverify,{'emailer':emailer});
});
});
</script>
The dajax function
#dajaxice_register(method='GET')
def sendEmail(emailer):
logger.warning("type: %s, %s" % (type(emailer),emailer))
email_body = "message"
emailer.addToMessage(email_body)
emailer.send()
message = "Email Sent"
return json.dumps({'message':message})
Here the logger statement returns: type: <type 'unicode'>, <Utils.SIMPL_Emailer instance at 0x103142ab8>. Is there any way to fix this so that I get my emailer object instead of a unicode string?
First try to understand what is happening:
On your template you're trying to save a Python object to a Javascript var:
var emailer = "{{emailer|safe}}";`
But it's not possible. When your template is rendered by Django what you really get is a call to object __str__() method and your Javascript will store the <Utils.SIMPL_Emailer instance at 0x103142ab8> value on your emailer var. And remember: this code run in the client browser. That's why you get an error when you remove the quotes.
To solve it you need to first serialize your emailer object (Turn it into something that could be represented as a String, for example, and then turned back to Python Object). But as pointed by Peter DeGlopper it is a very insecure approach. Never, ever deserialize an whole object that was public accessible. Instead send only the email data to your template. You can create a dictionary with this data, turn it into JSON (it's a serialization too, but this time you are serializating only data) and then pass it to your template.
So do not put your emailer on the template context. Instead create a dictonary and pass it to the template.
Then in your Python sendEmail(emailer) method you'll need to instanciate a new Emailer object and feed it with the data, like:
#dajaxice_register(method='GET')
def sendEmail(email_json):
email = json.loads(email_json) # email_json is a json with your email data only
logger.warning("type: %s, %s" % (type(email_json),email_json))
emailer = Emailer("<with all your params...>")
emailer.addToMessage(email.get('body'))
emailer.send()
message = "Email Sent"
return json.dumps({'message':message})
I have a front-end and back-end script that are working with one another. The front-end script of type JS does JSON.stringify on an array of strings and calls the backend script for validation on this string.
The backend script of type Perl grabs this string and does a decode_json from the Perl module JSON. At this point the Perl script is croaking.
I think the problem has to do with what's returned by JSON.stringify.
JS:
var jl = ["Flash", "WonderWoman", "BatMan", "SuperMan", "GreenLantern", "MartianManHunter", "HawkWoman"];
var $jl_string = JSON.stringify(jl);
// assume there is code here that makes an AJAX call which calls the backend script
Returns this:
"[\"Flash\", \"WonderWoman\", \"BatMan\", \"SuperMan\", \"GreenLantern\", \"MartianManHunter\", \"HawkWoman\"]"
Perl function that validates the above stringified string:
sub are_jl_members {
my ($jl_string) = #_;
print "<p>$jl_string</p>";
# Failing here. Why?
my $jl = decode_json $jl_string;
print Dumper([$jl]);
}
Thanks for the help.
The problem is the extra "\" in your $jl_string. Your JSON.stringify call is correct satanically.
How are you printing $jl_string here?
Returns this:
"[\"Flash\", \"WonderWoman\", \"BatMan\", \"SuperMan\", \"GreenLantern\", \"MartianManHunter\", \"HawkWoman\"]"