python 杂七杂八 :
subprocess.Popen(...)
python3 实现代码: 备注write 要使用bytes 在最后结果转为str 显示时才不会出现 b'' 这样的字节显示
import subprocess
obj = subprocess.Popen(["python3"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write(bytes('print(1)',encoding='utf-8'))
# obj.stdin.write('print 2 \n ')
# obj.stdin.write('print 3 \n ')
# obj.stdin.write('print 4 \n ')
obj.stdin.close()
cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close()
print(str(cmd_out,encoding='utf-8'))
print(cmd_error)
异常处理:
备注:python3 中
try:
except Exception as e :
______________________________________________________________
while True:
num1 = input('num1')
num2 = input("num2")
try:
num1 = int(num1)
num2 = int(num2)
result = num1 + num2
except Exception as e :
print("出现异常,信息如下:")
print(e)
其他异常
try: # 主代码块 pass except KeyError,e: # 异常时,执行该块 pass else: # 主代码块执行完,执行该块 pass finally: # 无论异常与否,最终执行该块 pass
主动异常和断言
while True: num1 = input('num1') num2 = input("num2") try: num1 = int(num1) raise Exception('错误了。。。') #主动异常 num2 = int(num2) assert 1 ==1 #断言 result = num1 + num2 print(result) except Exception as e : print("出现异常,信息如下:") print(e)