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.

1

1 Answer 1

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()

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. It works. Just to know: what does 'w' means?
that's for write access; it truncates the target file if itexists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.