【发布时间】:2021-04-11 04:49:44
【问题描述】:
和我在一起,我这里有一个非常复杂的设置(我很乐意让它变得更简单) 我有一个 nodejs 服务器正在运行(用于 localhost 访问),nodejs 正在读取文件并在浏览器中输出
这让我有可能拥有自己的服务器来测试多个事物,例如,我可以访问 localhost/test.html 或 localhost/web.php。而且效果很好。
现在我想控制灯光。我有一个可以做到这一点的 python 脚本(它在终端中运行良好)
现在我希望能够使用 nodejs 运行的 html 页面上的一个简单按钮来运行脚本。
我尝试了多种方法,包括 pythonshell、php,但找不到有效的方法..
所以我可以从 nodejs 在浏览器中输出的页面运行 python 脚本吗?
编辑:
这里更详细地介绍了 evreything 的运行方式: 我节点一个 app.js 运行一个简单的读取文件并获取 url
app.js
http = require("http"),
path = require("path"),
url = require("url"),
fs = require("fs");
function sendError(errCode, errString, response)
{
response.writeHead(errCode, {"Content-Type": "text/plain"});
response.write(errString + "\n");
response.end();
return;
}
function sendFile(err, file, response)
{
if(err) return sendError(500, err, response);
response.writeHead(200);
response.write(file, "binary");
response.end();
}
function getFile(exists, response, localpath)
{
if(!exists) return sendError(404, '404 Not Found', response);
fs.readFile(localpath, "binary",
function(err, file){ sendFile(err, file, response);});
}
function getFilename(request, response)
{
var urlpath = url.parse(request.url).pathname; // following domain or IP and port
var localpath = path.join(process.cwd(), urlpath); // if we are at root
fs.exists(localpath, function(result) { getFile(result, response, localpath)});
}
var server = http.createServer(getFilename);
server.listen(1000);
console.log("Server available...");
从那里我可以调用同一目录中的任何文件,因此我调用 index.html
index.html
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Index</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body class="text-white bg-dark">
<center>
<form method="post">
<input type="submit" value="OFF" name="OFF" onclick="turnOff()">
<input type="submit" value="ON" name="ON" onclick="turnOn()">
</form>
</center>
<script>
function turnOff(){
//something i need to call shell command python3 turnOff.py
}
function turnOn(){
//something i need to call shell command python3 turnOn.py
}
</script>
</body>
</html>
我有两个文件 turnOn.py 和 turnOff.py
谢谢
【问题讨论】:
-
您是否尝试过将脚本的输出写入文件,并在浏览器中显示文件内容?
-
我在同一个根目录下有一个 .py 文件,我只是找不到如何运行它