user7437554
user7437554

Reputation:

troubles when using a bash command inside a python script

I am trying this on python:

import os

process="find . -type f -name *.out*.xyz'"
print "the number of xyz files is %s" %os.system(process)

When i try it from command line it works, but from python it returns the number 0, when it is 4. I think there must be a problem with the use of os.system. Any help?

Upvotes: 1

Views: 49

Answers (2)

Arminius
Arminius

Reputation: 1169

Actually, if you really just need the number of files in Python, try this:

import pathlib
p = pathlib.Path('.')
files = [x for x in p.iterdir() if x.is_file() and x.match('*.csv')]
print("Number of files: {0}".format(len(files)))

Easier, Pythonic and you do not need to fork a sub-process.

Upvotes: 0

jimf
jimf

Reputation: 5137

Yes what you are getting is the return code "0" meaning "successfully completed, no errors" and not the stdout text output "4".

You should look here to get the output: Assign output of os.system to a variable and prevent it from being displayed on the screen

And here to learn about POSIX exit codes: https://en.wikipedia.org/wiki/Exit_status

Upvotes: 2

Related Questions