这是我的python 3.5 web服务器:
#!/usr/bin/env python35
PORT = 80
import http.server
httpd = http.server.HTTPServer( ("", PORT),http.server.CGIHTTPRequestHandler)
httpd.cgi_directories = ["/"]
httpd.serve_forever()问题是:文件没有执行。web浏览器只是输出文件的内容。
它遗漏了一些东西。
我对python不是很在行。
只是用它来创建一个完全由bash脚本组成的网站。
发布于 2017-02-06 02:04:09
这并不是那么微不足道,可能需要你几天来与全面发展的应用程序。我给出了一个小蓝图,您可以将其作为使用python和flask进行进一步开发的基础。
为了保持应用程序的简单性,我假设shell脚本与应用程序保存在同一目录中。要构建应用程序,您可以使用flask框架,这是一个微框架,它使得在python中构建简单的应用程序变得非常容易。Python有一个subprocess模块,可以调用该模块在后台执行外壳脚本。根url将提供目录中的文件以及指向这些文件的链接,如果这些文件被单击,则用户将被路由到另一个url,该url将具有所单击的bash脚本的输出。
因此,您的项目必须有两个文件。我们可以称之为my_server.py的python文件和一个模板文件: home.html保存在templates文件夹中,用于处理根文件夹中不同文件的显示。因此,您的根文件夹将如下所示。script.sh是一个示例脚本文件,保存在那里用于测试。您将在那里拥有自己的脚本文件。
drwxrwxr-x templates
-rwxr--r-- home.html
-rw-rw-r-- script.sh
-rwxr--r-- my_server.pyHome.html的内容:
<html>
<body>
<ul>
{% for i in data: %}
<li><a href="{{ url_for('script_file', filename=i)}}">
Files: {{ i }}
</a></li>
{% endfor %}
</ul>
</body>
</html>my_server.py的内容
import os
import subprocess
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/')
def get_data():
def file_in_dir():
for entry in make_tree(get_root_dir()):
yield entry
return render_template('home.html', data=file_in_dir())
@app.route('/<filename>')
def script_file(filename):
if ".sh" in filename:
shell_script = {'file_path': get_root_dir(), 'filename': filename}
subprocess.call("bash {file_path}/{filename} > out.txt".format(**shell_script), shell=True)
with open("out.txt") as f:
contents = f.read()
return contents
else:
return "Not an executable bash script"
def make_tree(path):
lst = "No files"
try: lst = os.listdir(path)
except OSError:
pass #ignore errors
return lst
def get_root_dir():
return os.path.dirname(os.path.realpath(__file__))
if __name__ == "__main__":
app.run()我希望这将足以让您入门。
https://stackoverflow.com/questions/42053060
复制相似问题