os.system and subprocess odd behavior

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Dec 14 23:47:09 CET 2012

On Fri, 14 Dec 2012 10:13:38 -0800, py_genetic wrote:

> Example of the issue for arguments sake:
> Platform Ubuntu server 12.04LTS, python 2.7
> Say file1.txt has "hello world" in it.
> subprocess.Popen("cat < file1 > file2", shell = True)
> subprocess.call("cat < file1 > file2", shell = True) 
> os.system("cat < file1 > file2")
> I'm finding that file2 IS created, but with 0bytes in it, this happens
> when I try any sort of cmd to the system of the nature where I'm putting
> the output into a file.

I cannot confirm this behaviour. It works for me. When I try it, all 
three code snippets work as expected:

[steve at ando ~]$ rm file2 file3 file4
[steve at ando ~]$ cat file1
hello world
[steve at ando ~]$ python
Python 2.7.2 (default, May 18 2012, 18:25:10)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
py> import os, subprocess
py> subprocess.Popen("cat < file1 > file2", shell = True)
<subprocess.Popen object at 0xb7e8a62c>
py> subprocess.call("cat < file1 > file3", shell = True)
py> os.system("cat < file1 > file4")
py> quit()
[steve at ando ~]$ cat file2
hello world
[steve at ando ~]$ cat file3
hello world
[steve at ando ~]$ cat file4
hello world

I have run this multiple times, as an unprivileged user, as the root 
user, and as sudo. It works perfectly every time.

Please check your code. Perhaps you have over-simplified the problem.


More information about the Python-list mailing list