According to the documentation of os.system
, the return is the Exit status of the command (and not the output of the command itself), and zero generally indicates that the command ran normally with no errors.
The output of the command is sent to the default output (for example, if it runs on the terminal, it will appear on the screen itself).
To get the output of the command the way you want it, use the module subprocess
:
import subprocess
cmd = "ls livros -1 | wc -l"
out = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, text=True)
print(out.stdout)
Since the output of the command is just a number, you can convert it to int
if you want:
quantidade = int(out.stdout.strip())
I used strip()
to remove the line break at the end, which is also returned in out.stdout
.
Obs: subprocess.run
added in Python 3.5 - for earlier versions, an alternative is to use Popen
:
p1 = subprocess.Popen(["ls", "/c/Users/hkotsubo/", "-1"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["wc", "-l"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
result = p2.communicate()
print(result[0].decode('ascii'))
# ou se quiser converter para int
quantidade = int(result[0])
print(quantidade)
it gives an error it says: Typeerror: Join() argument must be str or bytes, not 'list' You know how to fix this?
– Hugo Barbosa
@Hugobarbosa See working on Repl.it.
– Lacobus
mine does not return anything now, I managed to fix that problem but does not return anything the objective was that function to be inside the method init and when the GUI is booted it detects how many files are available in a given directory like this import os, os.path class test: def listar_files(directory='/books'): listing=[] for file in os.listdir(directory): file=os.path.Join(directory,file) if(os.path.isfile(file): listing.append(file) Return listing def init(self): a=self.list_files print(a) test
– Hugo Barbosa
How about that ?!
– Lacobus
It works well another question I created a directory called book and to pass in parameter I have to put /book right? and that when I try to pass it returns the error No such file or directory: '/book'
– Hugo Barbosa
@Hugobarbosa Has already tried
./livro
?– Lacobus