0

I would like to call system shell in a Python code and write the results in a text file. When I write this command:

call(["ls", "-lrt"])

The calling process works and print the files and folders list as an output on the screen. However, when I try to write the printed output in a text file (rather than screen), it does not work! I tried all these:

call(["ls", "-lrt", ">", "result.txt"])

call(["ls", "-lrt", "> result.txt"])

call(["ls -lrt > result.txt"])

But in the Linux shell this command "ls -lrt > result.txt" nicely works.

I am using Linux CentOS 7 and my Python version is 2.7.5.

I will be thankful if anyone can help me for this simple problem.

Amir
  • 637
  • 1
  • 6
  • 11
  • It has been already answered here using os.system http://stackoverflow.com/questions/3791465/python-os-system-for-command-line-call-linux-not-returning-what-it-should – mayanand Nov 07 '15 at 01:00

1 Answers1

3

use e.g. subprocess.call like this

subprocess.call(["ls",  "-lrt"], stdout=open("foo.txt",'w'))

The signature of the function

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

is rather self-explanatory; stdin , stdout and stderr are meant for fileobjects like those returned by open()

decltype_auto
  • 1,706
  • 10
  • 19
  • Thanks a lot. It works. Just to know: what does 'w' means? – Amir Nov 07 '15 at 00:52
  • [that's for *write* access](https://docs.python.org/2.7/tutorial/inputoutput.html#reading-and-writing-files); it truncates the target file if itexists. – decltype_auto Nov 07 '15 at 01:05