这是什么错误?python脚本linux

这是什么错误?python脚本linux,python,linux,subprocess,Python,Linux,Subprocess,程序获取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 impor

程序获取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之间)。

代码未正确缩进。你犯了什么错误?你能发布你的堆栈跟踪吗?自己运行代码,sr2222@hd1他是SO的新手,试图帮助他学会如何发布好的问题。另外,反正也不行,因为我没有*nix,也没有
home/juan
目录。一旦我解决了缩进问题,代码就会运行并给出输出。@user2410421,你希望它能给你什么?