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

标签 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 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/

相关文章:

python - 将数字日期转换为字典中的单词

python - 后验高斯过程(Python)

linux - 有什么可以替代Access的吗?

python - 你能像往常一样制作一个python子进程输出stdout和stderr,但也可以将输出捕获为字符串吗?

Python - 运行时间和内存使用方面的可扩展性很重要

Python:如何使用必须引用其容器的元素设计容器

linux - 如何在启动时将值传递给内置的 Linux 内核模块?

c - 如何向 Linux 系统添加/注册唯一的 errno 和相应的错误消息?

javascript - 从 Python 中的 Node 命令捕获输出

python - 从 Django 内部调用时,Subprocess.Popen 与交互式程序挂起