gpt4 book ai didi

python - 这是什么错误? linux 下的 python 脚本

转载 作者:太空宇宙 更新时间:2023-11-04 04:15:21 26 4
gpt4 key购买 nike

程序获取 ls 目录列表并打印项目的索引,然后要求选择一项,然后打印该项目,但我收到此错误:

./directory.py
from: can't read /var/mail/subprocess
./directory.py: línea 3: error sintáctico cerca del elemento inesperado `('
./directory.py: línea 3: `def listdir (path):'

这是我的代码

from subprocess import Popen, PIPE

def listdir (path):
p = Popen(['ls', path,'-t'] , shell=False, stdout=PIPE, close_fds=True)
return [path.rstrip('\n') for path in p.stdout.readlines()]

def find(f, seq):

for item in seq:
if f == item:
return item

def listshow(l,i):

for item in l:

print i, item
i = i + 1

dirlist = listdir("/home/juan/")
val = 0
listshow(dirlist, val)

while True:
try:
line = raw_input()
except EOFError:
if not line: break

print dirlist[line]

最佳答案

您正在使用字符串作为列表索引,因此它不起作用。更改这部分代码

while True:
try:
line = raw_input()
except EOFError:
if not line: break

有了这个

value = None
while True:
try:
line = raw_input()
if not line: break
else:
value = int(line)
break
except ValueError:
print "You have not provided a valid integer"

另请注意,您正在使用用户提供的索引,而没有检查它是否确实存在于数组中。所以你也可以这样做:

try:
print dirlist[line]
except IndexError:
print "Nope, that element does not exists..."

或者在获得数字后检查这一点(检查给定的数字是否在 0 和 len(dirlist)-1 之间)。

关于python - 这是什么错误? linux 下的 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16700779/

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