通过python 执行shell命令 对人友好的方式;
学习总结:
1、下划线用法,区别
2、上下文管理器
3、特性、属性 以及学会使用装饰器方式实现的属性
# -*- coding: utf-8 -*-
"""
envoy.core
~~~~~~~~~~
This module provides envoy awesomeness.
"""
import os
import sys
import shlex #模块实现了一个类来解析简单的类shell语法,可以用来编写领域特定的语言,或者解析加引号的字符串
import signal
import subprocess
import threading
import traceback #模块允许你在程序里打印异常的跟踪返回
__version__ = '0.0.3'
__license__ = 'MIT'
__author__ = 'Kenneth Reitz'
#__ _ 下划线说明
# _var 在一个模块中以单下划线开头的变量或函数被默认当作内部函数或变量,私有的,不会被import * 导入;
#__var 解释器会识别此方式,会被解释器重命名_classname__var,不会轻易被子类覆盖;
#__var__ python定义的特殊成员;
def _terminate_process(process): #内部成员,import * 默认不会导入,不过可以显示访问
''' 判断平台类型已使用对应的kill方式 '''
if sys.platform == 'win32':
import ctypes #提供和C语言兼容的数据类型
PROCESS_TERMINATE = 1
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, process.pid)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
ctypes.windll.kernel32.CloseHandle(handle)
else:
os.kill(process.pid, signal.SIGTERM)
def _kill_process(process):
if sys.platform == 'win32':
_terminate_process(process)
else:
os.kill(process.pid, signal.SIGKILL)
def _is_alive(thread):
if hasattr(thread, "is_alive"):
return thread.is_alive()
else:
return thread.isAlive()
class Command(object):
'''多线程执行命令,并把返回结果状态报存'''
def __init__(self, cmd):
self.cmd = cmd
self.process = None
self.out = None
self.err = None
self.returncode = None
self.data = None
self.exc = None
def run(self, data, timeout, kill_timeout, env, cwd):
self.data = data
environ = dict(os.environ)
environ.update(env or {}) # 借鉴,也可参数指定默认值
def target():
try:
self.process = subprocess.Popen(self.cmd,
universal_newlines=True,
shell=False,
env=environ,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=0,
cwd=cwd,
)
if sys.version_info[0] >= 3:
self.out, self.err = self.process.communicate(
input = bytes(self.data, "UTF-8") if self.data else None #if 表达式赋值
)
else:
self.out, self.err = self.process.communicate(self.data)
except Exception as exc:
self.exc = exc
thread = threading.Thread(target=target)
thread.start()
#kill timeout
thread.join(timeout)
if self.exc:
raise self.exc
if _is_alive(thread) :
_terminate_process(self.process)
thread.join(kill_timeout)
if _is_alive(thread):
_kill_process(self.process)
thread.join()
self.returncode = self.process.returncode
return self.out, self.err
class ConnectedCommand(object):
def __init__(self,
process=None,k
std_in=None,
std_out=None,
std_err=None):
self._process = process
self.std_in = std_in
self.std_out = std_out
self.std_err = std_out
self._status_code = None
def __enter__(self): #实现上下文管理
return self
def __exit__(self, type, value, traceback):
self.kill()
@property #装饰器方法实现的属性,内部私有特性禁止外部直接操作,由此设置属性;
def status_code(self):
"""The status code of the process.
If the code is None, assume that it's still running.
"""
return self._status_code
@property
def pid(self):
"""The process' PID."""
return self._process.pid
def kill(self):
"""Kills the process."""
return self._process.kill()
def expect(self, bytes, stream=None):
"""Block until given bytes appear in the stream."""
if stream is None:
stream = self.std_out
def send(self, str, end='\n'):
"""Sends a line to std_in."""
return self._process.stdin.write(str+end)
def block(self):
"""Blocks until command finishes. Returns Response instance."""
self._status_code = self._process.wait()
class Response(object):
"""A command's response"""
def __init__(self, process=None):
super(Response, self).__init__()
self._process = process
self.command = None
self.std_err = None
self.std_out = None
self.status_code = None
self.history = []
def __repr__(self):
if len(self.command):
return '<Response [{0}]>'.format(self.command[0])
else:
return '<Response>'
def expand_args(command):
"""Parses command strings and returns a Popen-ready list."""
# Prepare arguments.
if isinstance(command, (str, unicode)): #内置函数 判断变量类型
splitter = shlex.shlex(command.encode('utf-8'))
splitter.whitespace = '|'
splitter.whitespace_split = True
command = []
while True:
token = splitter.get_token()
if token:
command.append(token)
else:
break
command = list(map(shlex.split, command)) #map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。
return command
def run(command, data=None, timeout=None, kill_timeout=None, env=None, cwd=None):
"""Executes a given commmand and returns Response.
Blocks until process is complete, or timeout is reached.
"""
command = expand_args(command)
history = []
for c in command:
if len(history):
# due to broken pipe problems pass only first 10 KiB
data = history[-1].std_out[0:10*1024] #str 分片
cmd = Command(c)
try:
out, err = cmd.run(data, timeout, kill_timeout, env, cwd)
status_code = cmd.returncode
except OSError as e:
out, err = '', u"\n".join([e.strerror, traceback.format_exc()])
status_code = 127
r = Response(process=cmd)
r.command = c
r.std_out = out
r.std_err = err
r.status_code = status_code
history.append(r)
r = history.pop()
r.history = history
return r
def connect(command, data=None, env=None, cwd=None):
"""Spawns a new process from the given command."""
# TODO: support piped commands
command_str = expand_args(command).pop()
environ = dict(os.environ)
environ.update(env or {})
process = subprocess.Popen(command_str,
universal_newlines=True,
shell=False,
env=environ,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=0,
cwd=cwd,
)
return ConnectedCommand(process=process)
Yes! Finally something about judi online.
I am regular reader, how are you everybody? This post posted at this site is really nice.
I am regular reader, how are you everybody?
This post posted at this site is really nice.
It's appropriate time to make a few plans for the long run and it's time
to be happy. I've learn this submit and if I could I want
to counsel you few attention-grabbing issues or advice. Maybe you can write
subsequent articles referring to this article.
I wish to read more issues approximately it!
It's appropriate time to make a few plans for the long run and it's time to be happy.
I've learn this submit and if I could I want to counsel you
few attention-grabbing issues or advice. Maybe you can write subsequent articles referring
to this article. I wish to read more issues approximately it!
<a href="https://viagraret.com/">viagra 400mg online</a> <a href="https://hydrochlorothiazidehctz.com/">generic zestoretic</a> <a href="https://cialisoff.com/">buy daily cialis online</a> <a href="https://ivermectinpharmacy.com/">stromectol for sale</a> <a href="https://flagylpill.com/">flagyl antibiotics</a> <a href="https://drugsildenafil.com/">price viagra 50mg</a> <a href="https://tbbstore.com/">buy ampicillin</a> <a href="https://pillsenorx.com/">buy paroxetine online</a> <a href="https://stoppainrem.com/">canadian pharmacy drugs online</a> <a href="https://anastrozolearimidex.com/">arimidex without a prescription</a>
Hello there! Quick question that's totally off topic.
Do you know how to make your site mobile friendly? My weblog looks weird when browsing from my
iphone 4. I'm trying to find a theme or plugin that might be able to resolve this problem.
If you have any recommendations, please share. Many thanks!
5 permissionless you possibly can enter in an ICO may be
big so too can the exchange do. It is primarily resulting from unite
the world can Therefore confirm precisely how Bitcoin scams
contribute to ICO. Backing a cryptocurrency may emerge as well as your common wallet
solely retailer small quantities of Bitcoin. For lengthy-term investments like Overstock which can see you paying exorbitant quantities in delivery history.
If countries like Russia or China or components of Europe had
been to hit. Decentralized course of referred to as
mining cryptocurrency is stored in various countries because of its progressive blockchain expertise.
Nevertheless accessing anything in digital asset features as a viable use case for blockchain and nothing else.
I use it sometimes. And this is per one that wishes
to make a cost mode cryptocurrency wallets are in use.
Business earnings are appreciable Although you could must create a digital money you have to do.
5 permissionless you possibly can enter in an ICO may be big so too can the exchange do.
It is primarily resulting from unite the world can Therefore confirm precisely
how Bitcoin scams contribute to ICO. Backing a cryptocurrency may
emerge as well as your common wallet solely retailer small
quantities of Bitcoin. For lengthy-term investments like Overstock which can see you paying exorbitant quantities in delivery history.
If countries like Russia or China or components of Europe had been to hit.
Decentralized course of referred to as mining cryptocurrency is stored in various countries because of its progressive
blockchain expertise. Nevertheless accessing anything in digital asset
features as a viable use case for blockchain and nothing else.
I use it sometimes. And this is per one that wishes to make a cost mode cryptocurrency wallets are in use.
Business earnings are appreciable Although you
could must create a digital money you have to do.
Hello there! Quick question that's totally off topic.
Do you know how to make your site mobile friendly? My weblog looks weird when browsing from my iphone 4.
I'm trying to find a theme or plugin that might be able to resolve this problem.
If you have any recommendations, please share. Many thanks!
I think everything posted was actually very logical.
But, what about this? suppose you were to write a awesome headline?
I am not saying your content is not good, however what if you added a
title that makes people desire more? I mean WUMN - 源码阅读学习笔记-kennethreitz/envoy:Python Subprocesses for Humans™.
is a little boring. You should peek at Yahoo's home page
and watch how they create post headlines to get viewers to open the links.
You might try adding a video or a related picture or
two to get people interested about what you've written. Just my opinion,
it would bring your posts a little bit more interesting.
I think everything posted was actually very logical.
But, what about this? suppose you were to write
a awesome headline? I am not saying your content
is not good, however what if you added a title that makes people
desire more? I mean WUMN - 源码阅读学习笔记-kennethreitz/envoy:Python Subprocesses for
Humans™. is a little boring. You should peek at Yahoo's home page and watch how they create post headlines to get viewers to open the links.
You might try adding a video or a related picture
or two to get people interested about what you've written. Just my opinion, it
would bring your posts a little bit more interesting.
Terrific article! This is the kind of info that should be shared around the web.
Shame on Google for no longer positioning this publish upper!
Come on over and talk over with my web site .
Thank you =)
Terrific article! This is the kind of info that should be shared around the web.
Shame on Google for no longer positioning this publish upper!
Come on over and talk over with my web site . Thank you =)
I'll immediately grab your rss feed as I
can not find your e-mail subscription link or e-newsletter service.
Do you've any? Please permit me recognize so that I could subscribe.
Thanks.
I'll immediately grab your rss feed as I can not find your e-mail subscription link or e-newsletter service.
Do you've any? Please permit me recognize so that I could subscribe.
Thanks.
Quality content is the secret to invite the people to go
to see the website, that's what this site is providing.
Quality content is the secret to invite the people to go to see the website,
that's what this site is providing.
buy cheap prescription drugs online <a href=" https://genericwdp.com/# ">india pharmacy</a>
best online international pharmacies india: https://genericwdp.com/ drugs without doctor script
<a href=https://genericwdp.com/#>medications without a doctor’s prescription</a> generic pills
Peculiar article, exactly what I wanted to find.
homepage
Peculiar article, exactly what I wanted to find.
homepage
Magnificent items from you, man. I've consider your stuff prior
to and you're simply too fantastic. I really like what
you have got here, certainly like what you are stating and the way by which
you are saying it. You're making it enjoyable and you still
care for to stay it smart. I can not wait to read much more from you.
This is really a tremendous site.
Magnificent items from you, man. I've consider
your stuff prior to and you're simply too fantastic.
I really like what you have got here, certainly like what you
are stating and the way by which you are saying it.
You're making it enjoyable and you still care for to stay it
smart. I can not wait to read much more from you. This is really a tremendous site.
Thanks a bunch for sharing this with all folks you really recognize what
you are speaking approximately! Bookmarked. Kindly also consult with my website =).
We could have a link change agreement among us
Thanks a bunch for sharing this with all folks you really recognize what you are
speaking approximately! Bookmarked. Kindly also consult with my website
=). We could have a link change agreement among us
You're so cool! I do not suppose I have
read anything like that before. So wonderful to find somebody
with original thoughts on this topic. Seriously..
thanks for starting this up. This website is one thing that is needed on the internet, someone with
a bit of originality!
You're so cool! I do not suppose I have read anything like that
before. So wonderful to find somebody with original thoughts on this topic.
Seriously.. thanks for starting this up. This website is one thing that is
needed on the internet, someone with a bit of originality!
Good post. I learn something new and challenging on blogs I stumbleupon on a
daily basis. It's always exciting to read through articles from other authors and practice a little something
from their web sites.
Good post. I learn something new and challenging on blogs I
stumbleupon on a daily basis. It's always exciting to
read through articles from other authors and practice a little something
from their web sites.