0

I wanted to Run Python script through HTML button. I am not using any server.

I tried using local server but it's giving this error : jquery-3.3.1.min.js:2 GET http://127.0.0.1:8080/home/techm/Documents/labelImg-master/labelImg.py 404 (Not Found)

And i tried with out server also I get this error : jquery-3.3.1.min.js:2 Failed to load file:///home/techm/Documents/labelImg-master/labelImg.py: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

this is my HTML code :

<!DOCTYPE html>
<html>
  <head>    
  </head>
  <body>
    <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">

    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>


    <script>
        function goPython(){
            $.ajax({
              url: "/home/techm/Documents/labelImg-master/run.sh",
             context: document.body
            }).done(function() {
             alert('finished python script');;
            });
        }
    </script>
  </body>
</html>

Is there any other way I can click the button in HTML page and automatically it run python script.

dishcode
  • 23
  • 1
  • 2
  • 9
  • your code seems to open URL `/home/techm/Documents/labelImg-master/run.sh` - but the error messages say that `/home/techm/Documents/labelImg-master/labelImg.py` is not found ... that's unpossible – Jaromanda X Sep 04 '18 at 09:37
  • Hi please understand that you will need a server for executing python. Pure javascript or jquery(which is javascript itself) can run on browser level only. It can't access your system. Since python can't be run on browsers you need to use a server so that you get access to your system. Then you can use the server(python server, node server or whatever) to execute your script. – Chris Aby Antony Sep 04 '18 at 09:39
  • check this one https://stackoverflow.com/questions/10186813/how-to-run-cmd-exe-with-parameters-from-javascript – brk Sep 04 '18 at 09:43
  • @JaromandaX Actually, in run.sh script one file is there named labelImg.py – dishcode Sep 04 '18 at 09:45
  • 1
    @ChrisAbyAntony no no I don't want to run python script in browser itself but when you press the button, my HTML code has to execute python script. Like how we manually do in terminal to run python script. – dishcode Sep 04 '18 at 09:49

4 Answers4

1

How about to use Brython? It's a python interpreter for client-side.

Here is the site.

https://brython.info/index.html

You can use it like this,

<div id="editor">
    print(123)
</div>
<button id="btn">Run Python</button>

...

<script type="text/javascript" src="https://cdn.rawgit.com/brython-dev/brython/stable/www/src/brython.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/brython-dev/brython/stable/www/src/brython_stdlib.js"></script>
<script type="text/python">
    from browser import doc, window
    from browser import html

    def exec_python():
        exec(doc['editor'].value)

    doc['btn'].bind('click', exec_python)
</script>
Yuda
  • 343
  • 4
  • 15
0

You can't access your file system through javascript functions due to security.

The only thing, you can do, is to disable the security of your browser.

If you use Chrome, start your chrome like this:

C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:/tempFolderForChromeThings
moe asal
  • 750
  • 8
  • 24
Develobba
  • 716
  • 8
  • 22
0

Unfortunately, what you're trying to do won't be possible. To run your Python script that is located on your file system, you would have to run it in your terminal and this is not possible to do via your navigator.

I recommend you set up a quick server that does this for you.

node.js server:

const http = require('http');
const { exec } = require('child_process');
const fs = require('fs');

//create a server object:
http.createServer(function (req, res) {

  //if the request url is: localhost:8080
  if(req.url === "/"){
    fs.readFile("index.html", function(err, data){
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write(data);
      res.end();
    });
  //if the request url is: localhost:8080/run
  }else if(req.url === "/run"){


    exec('./ /home/techm/Documents/labelImg-master/run.sh', (error, stdout, stderr) => {
     if (error) {
       console.error(`exec error: ${error}`);
       res.write('Command has failed'); //write a response to the client
       res.end(); //end the response
       return;
     }
     console.log(`stdout: ${stdout}`);
     console.log(`stderr: ${stderr}`);

     res.write('Command has been run'); //write a response to the client
     res.end(); //end the response
    });
  }

}).listen(8080); //the server object listens on port 8080

Once you've put the above content in a file called (for example) server.js, run the server by typing node server.js in your terminal (in the same directory as that file)

Then your ajax should be something like this.

$.ajax({
  url: "/run",
  context: document.body
}).done(function(data) {
  //data should contain what the server responds, in this case "Command has been run"
  console.log(data);
});
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
  • thank you for quick suggestion . Let me know if you have any important link of how to do it through server. Because I never worked with server - client side – dishcode Sep 04 '18 at 09:50
  • @dishcode are you comfortable with javascript? If so I'd recommend you to use node.js. You can literally set it up in 5 mins. – kemicofa ghost Sep 04 '18 at 10:00
  • @dishcode there I've provided an exmaple. I haven't tested it, if you get any errors let me know. You'll need to install node.js btw https://nodejs.org/en/ – kemicofa ghost Sep 04 '18 at 10:08
  • Yes I am familiar with JavaScript. Let me try your example code. – dishcode Sep 04 '18 at 10:14
  • after everything setup, when I will run localhost:8080, I am getting "Command has been run" but I can't see anything with python script it's not running/openings. – dishcode Sep 04 '18 at 11:39
  • @dishcode then you probably have an error when trying to run your script. The information regarding that should be in the `error` parameter of the exec callback. Simpy do console.log(error) and see what your server says in your terminal. – kemicofa ghost Sep 04 '18 at 11:40
  • After running server.js, I am running my HTML file and it has button, if you click on it it will open a web page and if you press the button it will redirect to localhost where I kept my python script. – dishcode Sep 05 '18 at 04:57
  • This is HTML code : ` ` – dishcode Sep 05 '18 at 05:03
  • This is server code is same you gave and chrome's inspect is telling : `Failed to load localhost:8080: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. send @ jquery-3.3.1.min.js:2` – dishcode Sep 05 '18 at 05:05
  • any solution of this? – dishcode Sep 11 '18 at 04:24
  • @dishcode this is a typical CORS problem. If you get your server to provide the HTML page, then you could replace "http://localhost:8080" with simply "/". It's just a security issue. – kemicofa ghost Sep 11 '18 at 10:32
  • @dishcode I've updated the code to reflect what I was talking about. Make sure you have your index.html page right beside your server.js file. Then type localhost:8080 in the URL to get your HTML page. Then your AJAX request should just be /run for the script to run. I didn't test this but should be close to something working. – kemicofa ghost Sep 11 '18 at 10:42
0

I have discovered a very easy way to launch a python script from a browser button, but running outside the browser. You do not have to install any additional software. No server, no network permissions, no new protocol registry, no nothing is needed.

  1. Compile your python script to get a .pyc file. On the python shell:
import py_compile
py_compile.compile ('myscript.py')
  1. Define a button in the html:
<button type="button" onclick="runOnPython()">RunOnPython</button>
  1. Define a simple javascript function to be executed when the button is clicked:
function runOnPython() {
    window.open("myScript.pyc")
}

Make sure that path information are complete. Here for the sake of simplicity html and python script are assumed to be on the same directory. If different, provide full path info for the myScript.pyc file.

When you click the button, famous Open File With / Save File dialog box pops up. Default python exe is listed as the opening application. So, click once more. There it is. Your Python script starts to execute.

Unfortunately it is not very easy to eliminate the second button click; because the " always do the same for this type of file" option is disabled. Your setting made at Options -> File Download Preferences does not make any difference either. You have to edit MimeTypes.rdf file in profiles folder of the browser; which I did not try.

Above scenario is tested on Python 3.6.5 with Firefox 65.0

user2800464
  • 113
  • 3
  • 11