使用子进程延迟执行命令

2024-10-16 20:39:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图使用子进程从python脚本执行此命令:sleep 10 && sudo /etc/init.d/tractor-blade restart &

我希望python脚本完成(返回代码0)。然后,10秒后,我希望命令被执行。

这就是我所拥有的:

import sys, subprocess
command = ['sleep', '10', '&&', 'sudo', '/etc/init.d/tractor-blade', 'restart' '&']
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

# Catch stdout
sys.stdout.flush()
for line in iter(p.stdout.readline, b''):
    print(">>> " + line.rstrip())

但事情就是这样:

>>> sleep: invalid time interval `&&'
>>> sleep: invalid time interval `sudo'
>>> sleep: invalid time interval `/etc/init.d/tractor-blade'
>>> sleep: invalid time interval `restart'
>>> sleep: invalid time interval `&'
>>> Try `sleep --help' for more information.

我猜我的格式不对?

我需要在执行命令之前完成python脚本,这就是为什么我要给命令添加延迟。我的sudoers允许使用NOPASSWD执行这个“拖拉机刀片”,因此不需要密码。


Tags: 命令脚本timeinitstdoutsysetcsudo
2条回答

API的工作方式是,command中的第一个元素是subprocess.Popen将调用的程序。列表的其余部分被解析,然后作为参数输入到程序中。默认情况下,它们不会被解析为shell命令。

这是因为子进程可以在两种模式下工作:要么是作为参数传递的元组指定的进程,要么是使用shell执行字符串。区别在于shell参数。所以你可能想做的是:

command = "sleep 10 && sudo /etc/init.d/tractor-blade restart"
p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True, stderr=subprocess.STDOUT)

或:

time.sleep(10)
command = ['sudo', '/etc/init.d/tractor-blade', 'restart' '&']
subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

documentation

The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.

相关问题 更多 >