2

I will use ls as an example:

I tried:

str = call("ls")

str stored 0.

I tried:

str = call("ls>>txt.txt")

but had no luck (an error occured & txt.txt wasn't created).

How do I perform this straight-forward task.

[I had imported call]

1 Answers1

0

Edit: call simply runs a command in the shell, then returns the return value of that command. Since your ls was successful, call('ls') returned 0.

If you are simply trying to run ls, then I would suggest using glob:

from glob import glob
file_list = glob('*')

If you want to do something more complicated, my suggestion would be to use subprocess.Popen() like this:

from subprocess import Popen, PIPE

ls_proc = Popen('ls', stdout=PIPE, stderr=PIPE)
out, err = ls_proc.communicate()

Note, in the stdout and stderr keywords, PIPE can be replaced with any file-like object, so you can send the output to a file if you want. Also, you should read about Popen.communicate() prior to using it since if the command you call hangs, your python routine will also hang.

Vorticity
  • 4,582
  • 4
  • 32
  • 49
  • Once you have the process open by calling Popen, the object that is returned will have a communicate() attribute. As for piping to a file, you can use `ls_proc = Popen('ls', stdout=open('outfile.txt', 'w'))`. – Vorticity Aug 01 '13 at 00:52
  • Can you show me the errors? – Vorticity Aug 01 '13 at 00:58
  • I apologize, it's working :) I'm not very practised with python syntax. –  Aug 01 '13 at 01:04