Convert text into a tuple or list (Python)


Hi, I would like to convert a text into a tuple or list. The text got it out of here:

import os
passwd=os.system("cat /etc/passwd | tail -1")

Now that I have the variable passwd with the text I want, how do I convert it into a tuple or list?

asked by user96431 15.08.2018 в 19:05

1 answer


The first problem is that os.system does not capture the standard output, so passwd will only have the return value of the command, a 0 in case of success.

One way is to use os.popen() :

import os

with os.popen('cat /etc/passwd | tail -1','r') as p:
    lines = p.readlines()

With this, what you achieve is to capture the output and have in the variable lines the complete list of lines of the standard output of the executed command, although in your example you should only have a single line (for tail -1 ). Then to convert each line into a tuple, just subtract using the split() method indicating the field separator, in this case : .

for l in lines:
    tupla = l.split(":")
answered by 15.08.2018 в 19:44