简体   繁体   English

在HTML页面和python脚本之间传输数据

[英]transferring data between my HTML page and python script

I have a very simple HTML page for testing which has a simple dropdown menu: 我有一个非常简单的HTML测试页面,其中包含一个简单的下拉菜单:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="mySelect" onchange="copy();">
<option value="">Select a person:</option>
<option value="Value of m1" >m1</option>
<option value="Value of m2" >m2</option>
<option value="Value of m3" >m3</option>
 <option value="Value of m4" >m4</option>
</select>
<br>
<br>
<p>The value of your selected choice is: </p>
<div id="label"></div>
function copy() 
{
    var selected_value = document.getElementById("mySelect").value
    document.getElementById("label").innerHTML = selected_value
}
</script>
</body>
</html>

Now I want to transfer the value of the selection into my python script. 现在,我要将选择的值传输到我的python脚本中。 My python script has a function which uses the passed value as an argument to give a JSON file. 我的python脚本具有一个函数,该函数使用传递的值作为参数来提供JSON文件。 I want to pass the value and then run the script to produce my JSON file when I select something. 我想传递值,然后在选择某些内容时运行脚本以生成JSON文件。 This is just for testing but my final HTML page will have multiple dropdowns similar to this one each one transferring a value to my python which would be used as an argument. 这仅用于测试,但我的最终HTML页面将具有多个类似于此的下拉列表,每个下拉列表都将一个值传输到我的python中,该值将用作参数。 Everything is done locally using local host. 一切都使用本地主机在本地完成。 Any help would be appreciated! 任何帮助,将不胜感激!

Its a bit tricky. 有点棘手。 You have to use a form to send the data to a PHP-Web Server. 您必须使用表格将数据发送到PHP-Web服务器。 Then use shell_exec($command) to run your Python Script with parameters. 然后使用shell_exec($ command)运行带有参数的Python脚本。

Your PHP Script should look like this: 您的PHP脚本应如下所示:

<?php
$input = $_GET['mySelect'];
//sanitize and check the input

$cmd = escapeshellcmd('/usr/custom/test.py -p ' . $input);
//escape the command

$output = shell_exec($cmd);
//run the script

echo $output;
?>

It's very important to sanitize and check your user input otherwise an attacker could easily get acces to your server. 清理并检查用户输入非常重要,否则攻击者很容易就能获得服务器的访问权限。

See more: http://php.net/manual/en/function.shell-exec.php 查看更多: http : //php.net/manual/en/function.shell-exec.php

Notes from php.net 来自php.net的说明

This function can return NULL both when an error occurs or the program produces >no output. 当发生错误或程序没有输出时,此函数都可以返回NULL。 It is not possible to detect execution failures using this function. 使用此功能无法检测执行失败。 >exec() should be used when access to the program exit code is required." 需要访问程序退出代码时,应使用> exec()。”


This function is disabled when PHP is running in safe mode. 当PHP在安全模式下运行时,此功能被禁用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM