设置 crontab 的子进程调用
subprocess call to setup crontab
我正在尝试使用 python 中的子进程调用来添加 cron 作业条目:
from subprocess import call
call(["(crontab -l; echo '* * * * * ls -l | tee tresults.txt') | sort - | uniq - | crontab - "])
而且我不知道我做错了什么!这是错误:
我认为您在这里遇到问题的原因是 subprocess
中的 call
函数有两种调用方式(参考 Python 2.7 文档:https://docs.python.org/2/library/subprocess.html#frequently-used-arguments):
如果你使用call
和一个字符串作为参数,你还需要传递'shell=True':
call("a long command with many arguments", shell=True)
如果您不想调用 shell=True
,这在某些情况下可能很糟糕,您需要将每个参数附加到它自己的字符串中,如 [=35 中所示=] 文档示例:https://docs.python.org/2/library/subprocess.html#using-the-subprocess-module
call(["ls", "-l"])
对于你的情况,我会尝试在你的 call
调用中添加一个 shell=True
参数,看看是否有帮助。
默认情况下,subprocess.call()
不 运行 shell (/bin/sh
)。
您需要 emulate multiple pipes in Python 或直接通过 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)
我正在尝试使用 python 中的子进程调用来添加 cron 作业条目:
from subprocess import call
call(["(crontab -l; echo '* * * * * ls -l | tee tresults.txt') | sort - | uniq - | crontab - "])
而且我不知道我做错了什么!这是错误:
我认为您在这里遇到问题的原因是 subprocess
中的 call
函数有两种调用方式(参考 Python 2.7 文档:https://docs.python.org/2/library/subprocess.html#frequently-used-arguments):
如果你使用
call
和一个字符串作为参数,你还需要传递'shell=True':call("a long command with many arguments", shell=True)
如果您不想调用
shell=True
,这在某些情况下可能很糟糕,您需要将每个参数附加到它自己的字符串中,如 [=35 中所示=] 文档示例:https://docs.python.org/2/library/subprocess.html#using-the-subprocess-modulecall(["ls", "-l"])
对于你的情况,我会尝试在你的 call
调用中添加一个 shell=True
参数,看看是否有帮助。
subprocess.call()
不 运行 shell (/bin/sh
)。
您需要 emulate multiple pipes in Python 或直接通过 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)