我正在尝试运行一个 python 脚本,该脚本读取输入文件的内容并需要在输出文件中以逐行(逐行)格式显示。
Script is as below:
==============================
#!/usr/bin/python
# Usage : python loop_test1.py /home/cdn/test1.in /home/cdn/test11.out
from user_agents import parse
import sys,getopt
import csv
myopts, args = getopt.getopt(sys.argv[1:],"i:o:")
# open file
f = open (sys.argv[1],"r")
#sys.stdout = open(sys.argv[2], "w")
#sys.stdout=open(sys.argv[2],"w")
results= (user_agent.browser,user_agent.browser.family,user_agent.browser.version,user_agent.browser.version_string)
c = csv.writer(open(sys.argv[2],"wb"), delimiter="|")
c.writerows(results)
#f1.write("|".join(fields))
#Read whole file into data
data = f.readline()
# Print it
#line = 0
for line in iter(f):
# print line
#line + = 1
user_agent = parse(line)
print user_agent.browser # returns Browser(family=u'Mobile Safari', version=(5, 1), version_string='5.1')
print user_agent.browser.family,"|" # returns 'Mobile Safari'
print user_agent.browser.version # returns (5, 1)
print user_agent.browser.version_string # returns '5.1'
# Accessing user agent's operating system properties
print user_agent.os # returns OperatingSystem(family=u'iOS', version=(5, 1), version_string='5.1')
print user_agent.os.family # returns 'iOS'
print user_agent.os.version # returns (5, 1)
print user_agent.os.version_string # returns '5.1'
# Accessing user agent's device properties
print user_agent.device # returns Device(family='iPhone')
print user_agent.device.family # returns 'iPhone'
print user_agent.is_mobile # returns True
print user_agent.is_tablet # returns False
print user_agent.is_touch_capable # returns False
print user_agent.is_pc # returns False
print user_agent.is_bot # returns False
# Close the file
f.close()
我收到此错误:
回溯(最后一次调用):文件“loop_test1.py”,第 11 行,在 results=(user_agent.browser,user_agent.browser.family,user_agent.browser.version,user_agent.browser.version_string) NameError: name 'user_agent'没有定义
你们能帮我解决这个问题吗?