瀏覽代碼

add lister sources

master
Dimitri Merejkowsky 5 年之前
父節點
當前提交
a2f272d025
共有 3 個文件被更改,包括 75 次插入2 次删除
  1. +2
    -2
      sessions/python-13.md
  2. +42
    -0
      sources/lister/lister.py
  3. +31
    -0
      sources/lister/test_lister.py

+ 2
- 2
sessions/python-13.md 查看文件

@@ -252,7 +252,7 @@ On peut le voir si on utilise des parenthèses:
>>> generator
<generator object <genexpr> at 0x7f654c272138>
>>> list(generator)
[1, 2, 3]
[0, 1, 2]
```

Les générateurs sont "feignants": ils ne calculent leur valeurs que quand
@@ -263,7 +263,7 @@ c'est demandé
```python
>>> generator = (x for x in range(0, 3))
>>> list(generator)
[1, 2, 3]
[0, 1, 2]
>>> list(generator)
[]
```


+ 42
- 0
sources/lister/lister.py 查看文件

@@ -0,0 +1,42 @@
import sys
import os

def parse_args(args):
options = Options()
if "-l" in args:
options.show_modification_time= True
return options

class Options:
def __init__(self):
self.show_modification_time = False

class Entry:
def __init__(self,name):
self.name=name
self.is_directory=False
self.mtime=0
def get_entries():
names = os.listdir(".")
for name in names:
entry = Entry(name)
entry.mtime = os.stat(name).st_mtime
yield entry

def list_entries(entries,options):
for entry in entries:
if options.show_modification_time :
yield f"{entry.name} {entry.mtime}"
else:
yield entry.name
def main():
options=parse_args(sys.argv)
entries = get_entries()
lines = list_entries(entries,options)
for line in lines:
print(line)
if __name__=="__main__":
main()

+ 31
- 0
sources/lister/test_lister.py 查看文件

@@ -0,0 +1,31 @@
import lister

def test_parse_args_empty_list():
options = lister.parse_args([])
assert options.show_modification_time is False
def test_parse_args_dash_l():
options = lister.parse_args(["-l"])
assert options.show_modification_time is True
def test_list_empty_entries():
options = lister.Options()
assert list(lister.list_entries([], options)) == []

def get_listing(entries, show_modification_time=False):
options = lister.Options()
options.show_modification_time = show_modification_time
return list(lister.list_entries(entries, options))

def test_list_names():
foo_txt = lister.Entry("foo.txt")
entries = [foo_txt]
assert get_listing(entries, show_modification_time=False) == ["foo.txt"]
def test_list_mtimes():
foo_txt = lister.Entry("foo.txt")
foo_txt.mtime = 1559404640
entries = [foo_txt]
assert get_listing(entries, show_modification_time=True)== ["foo.txt 1559404640"]