简体   繁体   中英

How execute cat filename* in python

I'm really new to python and after several hours of looking I haven't been able to find a solution (or failed to understand the solutions provided by other people).

I wanted to check the contents of several files with the same initial name 'pid' followed by a non-consecutive integer in a folder to make sure they all contained the word 'done'. The files contain a single word.

My initial idea was to use

cat pid*

somehow get the outputs of that command into a list and then just transverse the list comparing the values

result = 'Finished'
for x in range(len(myList)):
    if 'done' not in myList[x]:
        result = 'Continue'
        break
if result == 'Finished':
    print 'Finished'

that was my idea, but I can't find the way of getting that list containing the output of cat.

After some digging around I gave up on the idea and made a really POOR implementation (I think) I'm sure there has to be a better solution

filedir = os.popen('ls','r')

for line in filedir:
    print line
    if 'pid' in line:
        filename = open(line.replace('\n', ''), 'r')
        firstline = filename.readline()
        print firstline
        if 'done' not in firstline:
            status = 'RUNNING'
            break
if status == 'DONE':
    print 'Finished'
else:
    print status

Any help is really appreciated!

You can use the glob module, which "finds all the pathnames matching a specified pattern according to the rules used by the Unix shell":

import glob
for fn in glob.glob('pid*'):
    with open(fn) as f:
        if 'done' in f.read():
            ...

Use glob to perform the wildcard match and then read the files.

And please... stop calling shell commands for things that can be easily done in python itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM