我创建了一个简单的应用程序,它打印出/etc/passwd
输出的可读信息,但在解析文件中的大多数条目后收到错误消息:
Traceback (most recent call last):
File "unpacking_args5.py", line 19, in <module>
uname, *fields, homedir, sh = user_info
ValueError: need more than 1 values to unpack
以下是代码:
import subprocess
# the return command output is a string because
# of universal_newlines set to True
output = subprocess.check_output(
['cat', '/etc/passwd'],
universal_newlines = True
)
# this command converts it into a list of user information on the system
output = output.split('\n')
# --------------------- If this is the value passed there's no error ---- #
# output = [
# 'ianhxc:x:1000:1000:ianHxc,,,:/home/ianhxc:/usr/bin/zsh'
# ]
for line in output:
user_info = line.strip().split(":")
uname, *fields, homedir, sh = user_info
print('Uname: %s' % uname)
print('Fields: %s' % fields)
print('homedir: %s' % homedir)
print('shell: %s' % (sh or 'None'))
print('')
这是命令的输出:
Uname: root
Fields: ['x', '0', '0', 'root']
homedir: /root
shell: /bin/bash
Uname: daemon
Fields: ['x', '1', '1', 'daemon']
homedir: /usr/sbin
shell: /usr/sbin/nologin
# ... many successful entries omitted ...
Uname: mysql
Fields: ['x', '999', '999', '']
homedir: /home/mysql
shell: None
Traceback (most recent call last):
File "unpacking_args5.py", line 19, in <module>
uname, *fields, homedir, sh = user_info
ValueError: need more than 1 values to unpack
我认为这与使用“明星运营商”有关。
答案 0 :(得分:2)
你的行中没有:
冒号;分割这些时,你只需要一个元素。
这可能是对其进行#
评论的行,例如:
>>> line = '#\n'
>>> user_info = line.strip().split(":")
>>> user_info
['#']
>>> uname, *fields, homedir, sh = user_info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 1 values to unpack
你可以跳过这些线;测试user_info
列表的长度:
for line in output:
user_info = line.strip().split(":")
if len(user_info) < 3:
continue # not enough fields to be valid
uname, *fields, homedir, sh = user_info
# etc.
请注意,在此使用subprocess
overkill ;您也可以直接阅读文件:
with open('/etc/passwd') as output:
for line in output:
user_info = line.strip().split(":")
if len(user_info) < 3:
continue # not enough fields to be valid
uname, *fields, homedir, sh = user_info
# etc.
答案 1 :(得分:1)
在出现错误时,user_info
未包含足够的元素来分配给uname
,fields
,homedir
和sh
。将该赋值语句放入try
/ except
块并让except
块打印出user_info
,这样您就可以找出使其窒息的输入。