wzcwts521
wzcwts521

Reputation: 15

why ">" doesn't work in subprocess.call in python2

seems like it breaks at two places, one is ">", two is "/tmp/testing".

Python 2.7.5 (default, Aug 29 2016, 10:12:21) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call(["ls", "-ltr", ">", "/tmp/testing"])
ls: cannot access >: No such file or directory
ls: cannot access /tmp/testing: No such file or directory
2
>>> exit()

I've googled, and find other way to achieve what I need.

with.open("/tmp/testing","w") as f:
    subprocess.call(["ls", "-ltr"], stdout=f)

Wondering why first script doesn't work.

Upvotes: 0

Views: 59

Answers (1)

Blckknght
Blckknght

Reputation: 104792

The > you're trying to use to redirect the output from ls is implemented by your shell, not by ls itself. When you use subprocess.call, it (by default) does not use a shell to run the program. You can change that by passing shell=True as an argument (you may also need to change how the command is passed).

Alternatively, you could handle the redirection of the output to the file yourself, using Python code instead of the shell. Try something like this:

with open('/tmp/testing', 'w') as out:
    subprocess.call(['ls', '-ltr'], stdout=out)

Upvotes: 2

Related Questions