【问题标题】:How to use cgi form input as variable in call to system command in Python script?如何在 Python 脚本中调用系统命令时使用 cgi 表单输入作为变量?
【发布时间】:2012-06-27 22:17:36
【问题描述】:

假设我在运行 apache 的 Ubuntu 12.04 Web 服务器上有一个这样的网页:

<html>
<head>
  <meta content="text/html; charset=ISO-8859-1"
  http-equiv="content-type">
  <title>Name Input</title>
</head>
  <body>
    <form action="./test.py" method="post"> 
      <p> Name: <input type="text" name="name" id="name" value=""/></p> 
      <input type="submit" value="Submit" />
    </form>
  </body>
</html>

我想使用 name 的值作为 shell 脚本的输入,该脚本由这样的 Python CGI 脚本调用。

test.py:

#!/usr/bin/env python
import commands, cgi, cgitb
form = cgi.FieldStorage() 
name = form.getvalue('name') 
result = commands.getoutput("/usr/lib/cgi-bin/test.sh name")
contents = pageTemplate.format(**locals())
print "Content-type: text/html\n\n"
print contents

在上面的示例代码中,name 应该如何传递给 test.sh?

为了完整起见,假设 pageTemplate 如下所示:

pageTemplate = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <meta content="text/html; charset=ISO-8859-1"
  http-equiv="content-type">
  <title>Name Output</title>
</head>
  <body>
    {result}
  </body>
</html>
'''

【问题讨论】:

    标签: python bash shell ubuntu cgi


    【解决方案1】:

    只需将其传递到命令中:

    result = commands.getoutput("/usr/lib/cgi-bin/test.sh %s" % name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-08
      • 2016-11-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      相关资源
      最近更新 更多