# -*- coding: utf-8 -*-
"""
Created on Thu Apr 11 14:13:42 2019

@author: xwl99
"""

import subprocess
import os
import sys
import io
import threading
import time
import gevent
import inspect
import ctypes
def printOnSc(cmd):
    for line in iter(cmd.stdout.readline,b''):
        print (line.decode('gbk'))
    '''
    while cmd.poll() is None:
        try:
            a=cmd.stdout.readline()
            print(a.decode('gbk'))
            time.sleep(1) 
        except Exception as e:
            print (e,"E")
            return
'''
def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")
 
 
def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)
startDir=os.getcwd()

p=subprocess.Popen("cmd.exe",shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
print(startDir)
cmd1="cd %s \nD:\n"%(startDir)

#f=sys.stdout
#sys.stdout=p.stdout
#so,se=p.communicate('dir\n'.encode())
#print(so.decode('gbk'))
p.stdin.write('dir\n'.encode())
p.stdin.flush()
outT=threading.Thread(target=printOnSc,args=(p,))
outT.start()
p.stdin.write('cd ..\ndir\n'.encode())
p.stdin.flush()



time.sleep(0.1)
print (len(threading.enumerate()))
print(outT)
stop_thread(outT)
print (len(threading.enumerate()))
p.kill()
print (len(threading.enumerate()))
#so,se=p.communicate('cd ..\ndir\n'.encode())
#print(so.decode('gbk'))
#p.stdin.write('cd ..\ndir\n'.encode())

#for line in iter(p.stdout.readline,b''):
   # print (line.decode('gbk'))
#sto,ste=p.communicate()
#print(sto.decode('gbk'))
print('Fin')

#print(tmp)

