【问题标题】:Run python script and display printed value on a website运行 python 脚本并在网站上显示打印值
【发布时间】:2015-03-08 06:38:58
【问题描述】:

我有一个 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>

有什么想法可以实现这一点吗?

【问题讨论】:

  • 用javascript重写你的函数有多难?是否存在需要您使用 python 的依赖项?
  • 这取决于我使用的 plc。在我的情况下,我使用 Wago - 它可以工作(一个 javascript - 唯一的解决方案)。但是其他的PLC只能通过Modbus Tcp或者串口通讯,这迫使你使用Python。

标签: javascript python plc


【解决方案1】:

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

这可能需要一些工作,但它有据可查,你应该学习很多。

【讨论】:

    【解决方案2】:

    首先,您需要使您的服务器能够运行 .py 文件(关键字:cgi-bin),然后将您的 .py 文件上传到您的 cgi-bin 文件夹(Windows 用户提示:使用“保存所有文件” Linux/Unix 格式” - 在 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 文件中,您需要将“webArguments”的地址添加到“Python Arguments”...在我的情况下,我必须将以下内容添加到我的“普通”脚本中:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 2010-12-09
      • 2017-05-13
      • 1970-01-01
      相关资源
      最近更新 更多