这是我的代码:
def cmdoutput(cmd1, flag):
finish = time.time() + 50
p = subprocess.Popen(cmd1, stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
while p.poll() is None:
time.sleep(1)
if finish < time.time():
os.kill(p.pid, signal.SIGTERM)
print "timed out and killed child, collecting what output exists so far"
if (flag == "1"):#To enable container
out, err = p.communicate(input='container\nzone1')
else:
out, err = p.communicate()
print (out)
return out
当我运行此脚本时,我得到了
Attribute Error: 'module' object has no attribute 'kill'.
我的代码出了什么问题?
答案 0 :(得分:1)
我认为你有自己的os.py
。
将print os.__file__
放在os.kill(...)
行之前,您将看到发生了什么。
<强>更新强>
os.kill is only available in unix in jython
而不是os.kill(...)
,请使用p.kill()
。
<强>更新强>
p.kill()
不起作用。 (至少在Windows + Jython 2.5.2,2.5.3中)。
p.pid
为无。
答案 1 :(得分:0)
更改您的代码如下。更改CPYTHON_EXECUTABLE_PATH
,CMDOUTPUT_SCRIPT_PATH
。
CPYTHON_EXECUTABLE_PATH = r'c:\python27\python.exe' # Change path to python.exe
CMDOUTPUT_SCRIPT_PATH = r'c:\users\falsetru\cmdoutput.py' # Change path to the script
def cmdoutput(cmd1, flag):
return subprocess.check_output([CPYTHON_EXECUTABLE_PATH, CMDOUTPUT_SCRIPT_PATH, flag])
将以下代码保存为cmdoutput.py
import subprocess
import sys
def cmdoutput(cmd1, flag):
finish = time.time() + 50
p = subprocess.Popen(cmd1, stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
while p.poll() is None:
time.sleep(1)
if finish < time.time():
p.kill()
return '<<timeout>>'
if flag == "1":
out, err = p.communicate('container\nzone1')
else:
out, err = p.communicate()
return out
if __name__ == '__main__':
cmd, flag = sys.argv[1:3]
print(cmdoutput(cmd, flag))