使用 os.system 的 python 超时

标签 python python-2.7 subprocess os.system

所以,我知道每个人都会告诉我使用 subprocess 模块,但我不能将它用于我正在处理的项目,因为 Piping 根本不想在我的系统上使用 wxpython 和 py2exe。

所以,我一直在使用 os.system 调用。我需要知道如何等待进程结束。 目前,我有

os.system(cmd)

而我的命令实际上可能需要很长时间才能执行,所以它通常会提前超时。 如何让我的程序等待 os.system?我试过 waitpid,但我猜它对 os.system 不起作用。

我正在为 Windows 开发,所以不幸的是我不能使用 fork 和 execvp。我手忙脚乱:(

最佳答案

您可以更正您的代码:

os.system('cmd')

关于子进程的额外解释:

import subprocess
ls_output = subprocess.check_output(['ls'])

运行外部命令

要运行外部命令而不与其交互,例如使用 os.system() 执行的操作,请使用 call() 函数。

import subprocess

# Simple command
subprocess.call('ls -l', shell=True)

$ python replace_os_system.py
total 16
-rw-r--r--   1 root8085  root8085     0 Jul  1 13:27 __init__.py
-rw-r--r--   1 root8085  root8085  1316 Jul  1 13:27 replace_os_system.py
-rw-r--r--   1 root8085  root8085  1167 Jul  1 13:27 replace_os_system.py~

# run cmd

import subprocess
l = subprocess.call(['cmd'])

额外的例子: 以三种不同的方式进行系统调用:

#! /usr/bin/env python
import subprocess
# Use a sequence of args
return_code = subprocess.call(["echo", "hello sequence"])

# Set shell=true so we can use a simple string for the command
return_code = subprocess.call("echo hello string", shell=True)

# subprocess.call() is equivalent to using subprocess.Popen() and wait()
proc = subprocess.Popen("echo hello popen", shell=True)
return_code = proc.wait() # wait for process to finish so we can get the return code

控制标准错误和标准输出:

#! /usr/bin/env python
import subprocess
# Put stderr and stdout into pipes
proc = subprocess.Popen("echo hello stdout; echo hello stderr >&2", \
        shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
return_code = proc.wait()
# Read from pipes
for line in proc.stdout:
    print("stdout: " + line.rstrip())
for line in proc.stderr:
    print("stderr: " + line.rstrip())

关于使用 os.system 的 python 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17868500/

相关文章:

python - 属性错误 : 'module' object has no attribute 'printable'

python - 使用 OpenCV Python 提取所有边界框

python - 通过 Python 的 subprocess 模块运行 mysqldump 既慢又冗长

python全局变量未在for循环中定义

python - 将Python字符串拆分为对列表

Python 子进程 readline() 挂起;不能使用普通选项

python - 在 Python 中处理 PIPE - Raspbian Linux

Python:如何添加对象的静态类数组?

python - 写一个递归函数来解决斐波那契

python - 使用OpenCV时永远弹跳Python Rocket