编程语言
首页 > 编程语言> > python os.system错误:“未定义全局名称’输出’”

python os.system错误:“未定义全局名称’输出’”

作者:互联网

新手在这里.任何帮助,将不胜感激..

我正在编写一个运行tcp pcap诊断工具的cgi脚本.如果我在bash中运行命令,它看起来像:

/home/fsoft/cap/capnostic -r 38350 /home/fsoft/brad.pcap > 38350

所以我想在python中做到这一点:

output = os.system('/home/fsoft/cap/capnostic -r' + port + directory+filename '>' + jobdir+filename

我有一种’>’的感觉事情搞砸了..但我似乎无法找到正确的语法..一旦我正确得到命令,我只能打印输出变量?

 print '%s' % (output)

输出可能是3页数据..

谢谢您的帮助.

这是我的完整代码:

#!/usr/bin/env python

import cgi, os
import cgitb; cgitb.enable()
import subprocess


form = cgi.FieldStorage()
port = form.getvalue("port")
filename = form.getvalue("filename")
directory = form.getvalue("directory")
jobdir = '/var/www/jobs/' + filename


def createdir():
 os.system('mkdir /var/www/jobs/' + filename)
createdir()

def capout():
 output = os.system('/home/fsoft/cap/capnostic -r %s %s%s > %s%s' % (port, directory,     filename, jobdir, filename))
capout()

def htmlout():
 print 'Content-type: text/html\n'
 print '<html>'
 print '<head>'
 print '<title>Capnostic Output</title>'
 print '</head>'
 print '<body>'
 print '<BR><BR><BR><center>'
 print '<table border=0>'
 print '<TR>'
 print '<TD><center>port = %s<BR>filename = %s<BR>Directory = %s<BR>Job Directory = %s</TD>' % (port,filename,directory,jobdir)
 print '</TR>'
 print '</table>'
 print '<BR><BR><BR>'
 print '%s' % (output)
 print '</body>'
 print '</html>'

htmlout()

它现在告诉我:

<type 'exceptions.NameError'>: global name 'output' is not defined 
  args = ("global name 'output' is not defined",) 
  message = "global name 'output' is not defined"

解决方法:

你错过了连接字符串和字符串之间的空格.您可以使用string formatting来简化任务,或者只需在需要的位置添加空格和空格:

output = os.system('/home/fsoft/cap/capnostic -r %s %s%s > %s%s' % (port, 
                   directory, filename, jobdir, filename))

注意:%s用于将每个变量视为字符串.

os.system的使用将替换为subprocess模块:

sts = os.system("mycmd" + " myarg")
# becomes 
sts = call("mycmd" + " myarg", shell=True)

要捕获输出,您需要使用Popen,其翻译如下:

def capout():
   cmd = '/home/fsoft/cap/capnostic -r %s %s%s > %s%s' % (port, 
                       directory, filename, jobdir, filename)
   process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   output, error = process.communicate()
   return output

output = capout()

标签:os-system,python
来源: https://codeday.me/bug/20190901/1786622.html