在终端中从URL运行Python脚本

2024-05-15 09:11:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道有没有什么方法可以从终端的url(www.blahblah.com/script.py)中执行python脚本而不将文件下载到磁盘?

谢谢!


Tags: 文件方法py脚本com终端urlwww
3条回答

你问的是所谓的CGI。Python为它提供了一个模块:
http://docs.python.org/library/cgi.html

但是CGI现在有点过时了,因为它通常是为python应用程序提供服务的非常低效的方法。最好使用某种类型的python web framework

Common Gateway Interface

A web server that supports CGI can be configured to interpret a URL that it serves as a reference to a CGI script. A common convention is to have a cgi-bin/ directory at the base of the directory tree and treat all executable files within it as CGI scripts. Another popular convention is to use filename extensions; for instance, if CGI scripts are consistently given the extension .cgi, the web server can be configured to interpret all such files as CGI scripts.
In the case of HTTP PUT or POSTs, the user-submitted data is provided to the program via the standard input. The web server creates a small and efficient subset of the environment variables passed to it and adds details pertinent to the execution of the program.

这如何适用于您的问题是,您的script.py需要首先位于cgi-bin或web服务器配置为识别该类型的类似位置中。其次,您需要使用cgipython模块来访问参数(还需要符合请求/响应格式)

您希望在客户机上运行还是在服务器上运行(这将返回结果)?

如果你想在客户端上运行它,它必须以某种方式下载。一个简单的方法是下载、运行、删除:

$ wget blahblah.com/script.py && (python script.py; rm script.py)

如果你想在服务器上运行这个,你可以像其他人提到的那样使用CGI。但是,根据您想做的事情,您可能希望改用web框架。

对于轻量级框架,请查看Flask。他们的文档非常优秀,我设法在一天内完成并运行了一些东西(我对Python和web服务器都很陌生)。

你要找的是:

wget -qO-  https://gist.githubusercontent.com/mattwarrenrnp/6ca5bbeb4959974fb4ac/raw/23196eba76b1f21210f530a05572e38349384e0d/print.py | python -

说明:

-q对于安静模式,隐藏试图解释为python的错误

O-将下载指向stdout

用管道将stdout发送到python,并用“-”告诉它从stdin执行。

警告:始终确保您信任这样运行的脚本。

相关问题 更多 >