Calling a Python script from Javascript, both loca

2019-06-06 08:16发布

I'm trying to run a python script from a local javascript file (part of a locally running HTML/javascript program).

I've been googling this for hours and found a lot of solutions, none of which actually work for me.

Here is the javascript:

$.ajax({

    type: "POST",
    url: "test.py",
    data: { param: " "}
    }).done(function( o ) {
        alert("OK");
});

The test.py file is in the same folder as the script/html file.

here is the script:

#!/usr/bin/python
import os
filepath = os.getcwd()
def MakeFile(file_name):
    temp_path = filepath + file_name
    with open(file_name, 'w') as f:
    f.write('''\
def print_success():
    print "sucesss"        
''')
    print 'Execution completed.'

MakeFile("bla.txt");

It works fine when run normally.

On my Firefox console I get a "not well formed" error and the script doesn't create a file. However, I can see that Firefox does fetch the script, as I can view it in my browser by clicking the file name.

3条回答
smile是对你的礼貌
2楼-- · 2019-06-06 08:19

So apparently, as has been pointed out, this can't be done, not like this. So I'm going to start a simple CGI python sever to server the HTML file, and execute the script. I've tested it and it works great!

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-06-06 08:23

There are three problems with your code.

First, when you call $.ajax(), it tries to parse the response as either JSON or HTML. To prevent it, use dataType: "text".

$.ajax({
    type: "POST",
    url: "111212.py",
    data: { param: " "}, 
    dataType: "text"
    }).done(function( o ) {
        alert("OK");
});

Second, fetching a local file from javascript may violate the Same Origin Policy, depending on the browser. See: Origin null is not allowed by Access-Control-Allow-Origin

An most important, fetching does not execute a file, it just reads it and returns as a string.

查看更多
Fickle 薄情
4楼-- · 2019-06-06 08:25

In order for the python script to execute it has to be deployed by a web server that supports it via CGI or WSGI, etc.

Check out the docs here: webservers

查看更多
登录 后发表回答