0

I'm trying to use a subprocess call in python to add a cron job entry:

from subprocess import call

call(["(crontab -l; echo '* * * * * ls -l | tee tresults.txt') | sort - | uniq - | crontab - "])

And I don't know what I'm doing wrong! This is the error:

enter image description here

rypel
  • 4,392
  • 2
  • 23
  • 36
Rod
  • 13,333
  • 28
  • 106
  • 203

2 Answers2

0

I think the reason you're having the problem here is that the call function from subprocess has two ways to be called (referencing the Python 2.7 docs: https://docs.python.org/2/library/subprocess.html#frequently-used-arguments):

  1. If you use call with a single string as an argument, you need to also pass 'shell=True':

    call("a long command with many arguments", shell=True)
    
  2. If you don't want to call shell=True, which can be bad in some cases, you need to append each argument in it's own string, like shown in the Python docs example: https://docs.python.org/2/library/subprocess.html#using-the-subprocess-module

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

In your case, I'd try adding a shell=True argument to your call call and see if that helps.

mprat
  • 2,391
  • 13
  • 31
0

subprocess.call() does not run the shell (/bin/sh) by default.

You either need to emulate multiple pipes in Python or just pass shell=True:

#!/usr/bin/env python
from subprocess import check_call

check_call("(crontab -l; echo '* * * * * ls -l | tee tresults.txt') | "
           "sort - | uniq - | crontab - ",
           shell=True)
Community
  • 1
  • 1
jfs
  • 374,366
  • 172
  • 933
  • 1,594
  • what if the check_call is running some long-running python external program. How would you end it immediately if desired? – Rod May 19 '15 at 23:50
  • It seems completely unrelated to the current question. If you have a new question; [post it as a question](http://stackoverflow.com/questions/ask). – jfs May 20 '15 at 07:10