gpt4 book ai didi

python 操作系统系统错误 : "global name ' output' is not defined"

转载 作者:太空宇宙 更新时间:2023-11-03 14:30:25 35 4
gpt4 key购买 nike

这里是新手。任何帮助将不胜感激..

我正在编写一个运行 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()

关于python 操作系统系统错误 : "global name ' output' is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11907537/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com