0

I have a bunch of different text files, and am trying to sort the texts into one file. I am using python's subprocess, and I wrote the following code

command_line = "sort -m 1.txt 2.txt > a.txt"
args = shlex.split(command_line)
subprocess.call(args)

and the subprocess.call(args) returned 2 as a result, and nothing was written in a.txt. Anything wrong with my code?

  • unrelated: `sort -m` does not sort the files. It merges *already sorted* files. – jfs Mar 15 '15 at 17:00
  • See also [Sorting text file by using Python](http://stackoverflow.com/q/14465154/4279) – jfs Mar 15 '15 at 17:07

1 Answers1

0

If you want to use the shell redirection operator > in your command line, you have to pass shell=True to subprocess.call. Otherwise, '>' and 'a.txt' are passed as command line arguments to sort. With shell=True, the command line is passed to and interpreted by an actual shell, and you should therefore not shlex.split it. It may be easier to use os.system instead of subprocess.call, which uses a shell by default.

fpbhb
  • 1,469
  • 10
  • 22
  • "have to" is a bit strong. `call('sort -m 1.txt 2.txt'.split(), stdout=open('a.out', 'w'))` works without `shell=True`. See answers to the duplicate question – jfs Mar 15 '15 at 17:08
  • One "has to" if one wants to use an actual shell command line. I will clarify the answer. – fpbhb Mar 15 '15 at 17:38