Transfer array from python to javascript - Stack Overflow

I have a test.txt file that has two columns of data (x's and y's), eg:#test.txt1 232 2344

I have a test.txt file that has two columns of data (x's and y's), eg:

#test.txt
1 23
2 234
4 52
43 5
3 35

And a python program that reads in these values and stores them in x and y as so:

#test.py
# Read the file.
f = open('test.txt', 'r')

# read the whole file into a single variable, which is a list of every  row of the file.
lines = f.readlines()
f.close()

# initialize some variable to be lists:
x = []
y = []

# scan the rows of the file stored in lines, and put the values into some variables:
for line in lines:
    p = line.split()
    x.append(float(p[0]))
    y.append(float(p[1]))

I want to take these values stored in x and y and transfer them to two similar arrays in a javascript program to display them as a graph. How can I transfer between python and javascript?

I have a test.txt file that has two columns of data (x's and y's), eg:

#test.txt
1 23
2 234
4 52
43 5
3 35

And a python program that reads in these values and stores them in x and y as so:

#test.py
# Read the file.
f = open('test.txt', 'r')

# read the whole file into a single variable, which is a list of every  row of the file.
lines = f.readlines()
f.close()

# initialize some variable to be lists:
x = []
y = []

# scan the rows of the file stored in lines, and put the values into some variables:
for line in lines:
    p = line.split()
    x.append(float(p[0]))
    y.append(float(p[1]))

I want to take these values stored in x and y and transfer them to two similar arrays in a javascript program to display them as a graph. How can I transfer between python and javascript?

Share Improve this question asked Feb 14, 2016 at 17:27 Kareem ArabKareem Arab 1051 silver badge10 bronze badges 1
  • Either store the values in a database and use a server side language or invoke a webpage from python and pass it as a parameter(either using GET or structured using json) – riteshtch Commented Feb 14, 2016 at 17:34
Add a ment  | 

4 Answers 4

Reset to default 3

Your question is slightly vague. There are two possible ways your question can be interpreted, here are the corresponding answers:

  1. Your python code needs to transfer them to some javascript running in the browser/node.js application. In order to do this, the Python half of your application would need to either store the data in a database and expose the data via some sort of API, which the javascript half could consume. To go a little fancier, you could set up a connection between the two web servers (e.g. socket.io) and have the Python half send the arrays over the connection as they're created.
  2. This is what I believe you're trying to do based on the code you've posted: Preprocess some data in Python, and then pass it over to some other javascript piece of the puzzle where there's no real-time aspect to it.

    In this case, you could simply write the arrays to JSON, and parse that in Javascript. To write to a file, you could do:

    import json
    data = {'x': x, 'y': y}
    # To write to a file:
    with open("output.json", "w") as f:
        json.dump(data, f)
    
    # To print out the JSON string (which you could then hardcode into the JS)
    json.dumps(data)
    

Its unclear as to why you want to transfer this, but you can write it out into a js file simply by formatting the list into var someList = [[x1,y1], [x2,y2]].

Would be easier to build the string up withing from line in lines but in case you do have actual need of maintaining separate x and y lists

zippedList = list(list(zipped) for zipped in zip(xList,yList))
print('var someList = {};'.format(zippedList))

which gives you

var someList = [[1, 23], [2, 234], [4, 52], [43, 5], [3, 35]];

Write this out to a js file as needed or append to an existing html as

with open('index.html','a') as f:
    f.write('<script> var transferredList={}; </script>'.format(zippedList))

Because you mention "display" together with JavaScript, I somewhat assume that your goal is to have JavaScript in a web browser displaying the data that your python script reads from the file in the backend. Transferring from backend python to frontend JavaScript is a piece of cake, because both languages "speak" JSON.

In the backend, you will do something like

import json
response = json.dumps(response_object)

and in the frontend, you can right away use

var responseObject = JSON.parse(responseString);

It is also quite clear how the frontend will call the backend, namely using ajax, usually wrapped in a handy library like jQuery.

The field opens, when it es to making your python script run in a web server. A good starting point for this would be the Python How-To for using python in the web. You will have to consult with your web hosting service, too, because most hosters have clear guidance whether they admit CGIor, for example FastCGI. Once this is clear, maybe you want to take a look at the Flask micro-framework or something similar, which are offering many services you will need right out-of-the-box.

I have mentioned all the buzzwords here to enable your own investigation ;)

I didn't put the arrays stored in variables x and y, but you can do it if you know at least a bit of JavaScript.

var Request=new XMLHttpRequest();//request object
Request.open("GET","test.txt",true);
/*
 * Open request;
 * Take 2 arguments, but third is optional (async).
 * If you want async, then set onreadystatechange instead of onload event
*/
Request.onreadystatechange=function(){
    if(this.status==400){//status is okay
        var Lines=this.responseText.split("\n");
        alert(Lines[0])//will alert the first line
    }
    /*
     * this.status>=500 are request issues or user network delay
     * this.status=404 means file not found
    */
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744135221a4560026.html

相关推荐

  • Transfer array from python to javascript - Stack Overflow

    I have a test.txt file that has two columns of data (x's and y's), eg:#test.txt1 232 2344

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信