Abh*_*kar 5 python future python-2.7 python-3.x
我想将subprocess模块从py v3.3 导入到v2.7,以便能够使用该timeout功能。
看了几篇文章后,我尝试了
from __future__ import subprocess
Run Code Online (Sandbox Code Playgroud)
但它说:
SyntaxError: future feature subprocess is not defined
Run Code Online (Sandbox Code Playgroud)
然后我发现未来没有任何功能subprocess。
那么我应该subprocess从哪里导入v3.3?
我认为向后移植是个好主意。这里有一个比较subprocess.call。timeout请注意,在 Python2 中,后面带有命名参数*popenargs是一个语法错误,因此向后移植有一个解决方法。其他函数的超时参数的处理方式类似。如果您对超时的实际实现方式感兴趣,您应该查看该wait方法。Popen
def call(*popenargs, **kwargs):
"""Run command with arguments. Wait for command to complete, then
return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
"""
return Popen(*popenargs, **kwargs).wait()
Run Code Online (Sandbox Code Playgroud)
def call(*popenargs, timeout=None, **kwargs):
"""Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
"""
with Popen(*popenargs, **kwargs) as p:
try:
return p.wait(timeout=timeout)
except:
p.kill()
p.wait()
raise
Run Code Online (Sandbox Code Playgroud)
def call(*popenargs, **kwargs):
"""Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
"""
timeout = kwargs.pop('timeout', None)
p = Popen(*popenargs, **kwargs)
try:
return p.wait(timeout=timeout)
except TimeoutExpired:
p.kill()
p.wait()
raise
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
842 次 |
| 最近记录: |