首页 > 解决方案 > apache可以运行不可执行的python脚本吗?

问题描述

我设置了 Ubuntu 服务器 18.04 LTS、LAMP 和 mod_mono(顺便说一句,现在它似乎可以与 PHP 一起正常工作。)让 python 也可以工作;起初它给出了一个 HTTP“内部服务器错误”消息。sudo chmod +x myfile.py修复了此错误,python 生成的代码显示正常。但是,只要从文件中删除执行权限(例如通过上传文件的新版本),执行位就会被剥离并再次中断。

使用 incrontab 实现了一种解决方法,其中监控 cgi-bin 文件夹的更改以及导致chmod +x %f在其上运行的任何新写入。这工作了一段时间,然后停止了,充其量似乎是一个笨拙的解决方案。Perl、PHP,甚至 ASPX 都不需要标记为可执行 - 只有 python。

Apache 有什么方法可以在没有标记为可执行文件的情况下“运行”python?

标签: pythonapachewebserverchmodubuntu-18.04

解决方案


如果没有在 .py 文件上设置执行位,我认为 Apache 无法提供已执行的 python 脚本。

但这里有一个解决方法:只需将该文件标记为可执行文件,而是保留import第二个 python 文件。第二个文件不需要标记为可执行文件。

myfile.py(标记为可执行和只读 - 与 apache 一起使用):

#!/usr/bin/python3
# enable debugging
# helper to run the other, non-executable file
# do not add .py to the import "filename"
import myfile2

myfile 2 .py(仅标记为 RW,自由编辑此文件):

# this is the code which can change frequently
# and does not need to be marked executable...
print("Content-type: text/html\n\n")
print("<html><head><title>Python</title></head>")
print("<body>Hello, World!</body></html>")

推荐阅读