You could use package command_runner which will deal with timeouts, encoding etc on Unix and Windows platforms and provides the exit code so you know when the command fails.
Grab it with python -m pip install command_runner
Use it with
from command_runner import command_runner
all_output = []
file= 'labels.txt'
command = "tail -1 {}".format(file)
exit_code, output = command_runner(command, shell=True, timeout=30)
if exit_code == 0:
all_output.append(output)
print(all_output)
If you happen to need to iter over files in a given directory, you might use ofunctions.file_utils.
Grab it with python -m pip install ofunctions.file_utils
Use it like:
from ofunctions.file_utils import get_files_recursive
files = get_files_recursive('/my/folder', ext_include_list='.txt')
for file in files:
exit_code, output = command_runner('tail -1 {}'.format(file), timeout=30)
if exit_code == 0:
print(output)
DISCLAIMER: I am the author of command_runner package.
dirserves no purpose, sincediris then used as a loop variable in theforloop. You might as well remove that line from the post. What's relevant issubdirs, which is unknown.