How to catch a bash error when the script is run through python

I am trying to run a bash (or sh) script through a python script like so:

import os
cmd="/bin/echo {1..200000}"
out=os.system(cmd)

However, the command does not run and I get the following error:

/bin/echo: Argument list too long

I want to be able to capture this error specifically in my python script. try/except does not work here as it is not a python error, hence I want to know if there is any other way to capture this.

Upvotes: 0

Views: 593

Answers (1)

Frank Merrow
Frank Merrow

Reputation: 1009

The problem is that the error isn't happening in Python. The error happens in bash which is running as a separate process at that point. Take a look at the Python module "subprocess". It is more complex to set up than os.system(), but it allows you to capture stdin and stdout and process them after the process has terminated.

Upvotes: 4

Related Questions