Behavior of os.system() with redirection 
Author Message
 Behavior of os.system() with redirection

Well, I'm scratching my head over the following:

#!/usr/bin/python
import os
print "hi"
os.system("ls -l > results")
os.system("cat results")

Now, if I run the program, I get the following:


hi
total 0
-rw-rw-r--    1 mfenner  mfenner         0 Jan  2 15:21 results

which is all well and good.

However, if I redirect the output:

and THEN look at the results:

total 0
-rw-rw-r--    1 mfenner  mfenner         0 Jan  2 15:21 out
-rw-rw-r--    1 mfenner  mfenner         0 Jan  2 15:21 results
hi

I get something quite a bit different.  Now, I'm not concerned with
the extra file ("out") since that is an artifact of the redirection.
However, I am concerned about the "hi" being AFTER the "ls" output in
one case and BEFORE it in the other.

What's going on here?  How can I get a uniform ("hi" always first)
behavior?

Regards,
Mark



Mon, 21 Jun 2004 04:24:53 GMT  
 Behavior of os.system() with redirection

Quote:

> What's going on here?  

sys.stdout is buffered. The subprocess completes first, and writes to
the file. Then python completes, and writes the sys.stdout buffer to
the file.

Quote:
> How can I get a uniform ("hi" always first) behavior?

You can call sys.stdout.flush. Alternatively, you can invoke python
with -u, or set the PYTHONUNBUFFERED environment variable.

However, I would not recommend to invoke /bin/ls through
os.system. Instead, use os.listdir.

Regards,
Martin



Mon, 21 Jun 2004 06:06:14 GMT  
 Behavior of os.system() with redirection

Quote:
> However, I would not recommend to invoke /bin/ls through
> os.system. Instead, use os.listdir.

Thanks for your response.  In reality, I'm using a different program
(another script) written in R.  Since I haven't looked into higher
level interfaces for Python/R, I'm just using the system call.  This
was just a toy example to prevent posting 100s of lines of codes when
that had the essence of the problem.

Regards,
Mark



Tue, 22 Jun 2004 01:20:12 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. os.system() with redirection

2. unexpected os.system behavior on windows NT

3. New Behavior of os.system() in Python 2.0?

4. VRML, multi-agent system, behavior, expert system

5. Help: Simple redirection in REXX, OS/2

6. redirection in OS/2

7. OS/2 redirection

8. OS/2 redirection

9. More redirection in OS/2

10. redirection of SAY in OS/2 rexx

11. Redirection in C System command from within Ada

12. os.popen() vs os.system()

 

 
Powered by phpBB® Forum Software