运行python脚本并在网站上显示打印值

时间:2015-03-06 15:36:11

标签: javascript python plc

我有一个Python脚本,用于打印从与我的PC连接在同一网络上的PLC发送的当前值。

#!/usr/bin/python
#fetchVar.py argument-with-plc-variable-name
#some script to connect to PLC and fetch
#current value of variable sent as argument
print plcVar

脚本有效 - 这意味着每次运行此脚本时,我都会打印出我想要的变量的更新值。例如:

  

python fetchVar.py aiTemperature

     

15

这意味着,PLC中变量名为" aiTemperature"是15岁。 我试图在HTML页面中显示打印温度,这是我到目前为止所得到的:

<body onload="varupdate()">
    <script language="JavaScript">
        var int=self.setInterval("varupdate()",2000); // update Temperature every two seconds

        function varupdate() {
            // somehow run "python fetchVar.py aiTemperature"
            var x = ????;       //The printed value from getVar.py should be saved here
            document.getElementById("var1").innerHTML="Current Temperature = " + x;
        }
    </script>
    <div id="var1"></div>
</body>

我是如何实现这一目标的?

2 个答案:

答案 0 :(得分:0)

一个想法是让你的python脚本使用HTTP request handler回答获取请求。然后,您必须在JavaScript文件中的ajax中发送请求以获取所需的值。

这可能需要一些工作,但它有详细记录,你应该学到很多东西。

答案 1 :(得分:0)

首先,您需要启用服务器运行.py文件(关键字:cgi-bin),然后将.py文件上传到cgi-bin文件夹(Windows用户提示:用&保存所有文件) #34; Linux / Unix格式&#34; - 在npp上转到编辑/ EOL转换/ Linux格式。)

在我的HTML上:

<head>
<script src="jquery-2.0.3.js"></script>
<script>
    $(function ReadTemperature() {
        $.ajax({
            url: "http://my-server/cgi-bin/fetchVar.py",
            type: "post",
            datatype: "html",
            data: {
                webArguments: "aiTemperature" //Arguments you want to send to your .py
            },
            success: function(response){
                    $("#aiTemperature").html(response);
            },
            complete: function() {
                setTimeout(ReadTemperature, 2000);   //Refresh value every 2 seconds
            }
        });
    });
</script>
</head>
<body>
    <p>Current temperature: <div id="aiTemperature"></div> °C.</p>
</body>

在Python文件中,您需要添加&#34; webArguments&#34;的地址。 to&#34; Python Arguments&#34; ...在我的情况下,我必须将以下内容添加到我的&#34; normal&#34;脚本:

import cgi, cgitb
print "Content-type: text/html\n\n"    #for showing print on HTML
data = cgi.FieldStorage()
argument = data["webArguments"].value    #argument = name of PLC i need to fetch
#some script for connecting to PLC and reading current value of 
#variable  with name "argument", in this example "aiTemperature"
print plcVar
相关问题