Why is os.system behaving this way?

This is the place for queries that don't fit in any of the other categories.

Why is os.system behaving this way?

Postby DevynCJohnson » Sat May 25, 2013 3:09 pm

Why does os.system behave in this way and how can a save the real output?

Code: Select all
>>> VAR = os.system('date')
Sat May 25 11:06:23 EDT 2013
>>> print(VAR)
0


I want to save "Sat May 25 11:06:23 EDT 2013" not the exit status. How can I prevent the exit status from printing? Would subprocess work better? Keep in mind that I am using Python3.x.
Ubuntu 13.04 | Python3.3
User avatar
DevynCJohnson
 
Posts: 21
Joined: Sat May 25, 2013 1:53 pm

Re: Why is os.system behaving this way?

Postby stranac » Sat May 25, 2013 3:16 pm

os.system() returns the exit code of the command.

Yes, subprocess would work better, and you should always use it instead of os.system().
Specifically, you probably want to use subprocess.check_output() here.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1115
Joined: Thu Feb 07, 2013 3:42 pm

Re: Why is os.system behaving this way?

Postby DevynCJohnson » Sat May 25, 2013 7:13 pm

Thank you. I found that this command is a great substitute:

Code: Select all
subprocess.getoutput('SOME_BASH_COMMNAD')


I would like to know if there is a way to prevent os.system from doing that. It makes the command useless, at least with my programming.
Ubuntu 13.04 | Python3.3
User avatar
DevynCJohnson
 
Posts: 21
Joined: Sat May 25, 2013 1:53 pm

Re: Why is os.system behaving this way?

Postby micseydel » Sat May 25, 2013 10:20 pm

DevynCJohnson wrote:I would like to know if there is a way to prevent os.system from doing that. It makes the command useless, at least with my programming.

It's doing exactly what it's supposed to do, and if that doesn't work for you, then you should just use the tool that does do what you want.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1266
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Why is os.system behaving this way?

Postby DevynCJohnson » Sun May 26, 2013 12:03 am

Thank you, micseydel. I did not know that made os.system was made to do that without an option not to do so. It seems odd to me, but thankfully, I have found an excellent substitute.

Code: Select all
subprocess.getoutput('date')


Thank you everyone for your help.
Ubuntu 13.04 | Python3.3
User avatar
DevynCJohnson
 
Posts: 21
Joined: Sat May 25, 2013 1:53 pm


Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot] and 3 guests