python 调用 powershell
2022/4/2 7:50:31
本文主要是介绍python 调用 powershell,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
python3
import os from glob import glob import subprocess as sp class PowerShell: # from scapy def __init__(self, coding, ): cmd = [self._where('PowerShell.exe'), "-NoLogo", "-NonInteractive", # Do not print headers "-Command", "-"] # Listen commands from stdin startupinfo = sp.STARTUPINFO() startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW self.popen = sp.Popen(cmd, stdout=sp.PIPE, stdin=sp.PIPE, stderr=sp.STDOUT, startupinfo=startupinfo) self.coding = coding def __enter__(self): return self def __exit__(self, a, b, c): self.popen.kill() def run(self, cmd, timeout=15): b_cmd = cmd.encode(encoding=self.coding) try: b_outs, errs = self.popen.communicate(b_cmd, timeout=timeout) except sp.TimeoutExpired: self.popen.kill() b_outs, errs = self.popen.communicate() outs = b_outs.decode(encoding=self.coding) return outs, errs @staticmethod def _where(filename, dirs=None, env="PATH"): """Find file in current dir, in deep_lookup cache or in system path""" if dirs is None: dirs = [] if not isinstance(dirs, list): dirs = [dirs] if glob(filename): return filename paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs try: return next(os.path.normpath(match) for path in paths for match in glob(os.path.join(path, filename)) if match) except (StopIteration, RuntimeError): raise IOError("File not found: %s" % filename) if __name__ == '__main__': # Example: with PowerShell('GBK') as ps: outs, errs = ps.run(r'Get-ChildItem G:\test1 -recurse|?{$_.Name -like "test*"}|select Name') #print('error:', os.linesep, errs) #print('output:', os.linesep, outs) print(outs)
python2
import os from glob import glob import subprocess as sp class PowerShell: # from scapy def __init__(self, coding, ): cmd = [self._where('PowerShell.exe'), "-NoLogo", "-NonInteractive", # Do not print headers "-Command", "-"] # Listen commands from stdin startupinfo = sp.STARTUPINFO() startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW self.popen = sp.Popen(cmd, stdout=sp.PIPE, stdin=sp.PIPE, stderr=sp.STDOUT, startupinfo=startupinfo) self.coding = coding def __enter__(self): return self def __exit__(self, a, b, c): self.popen.kill() def run(self, cmd): b_cmd = cmd.encode(encoding=self.coding) try: b_outs, errs = self.popen.communicate(b_cmd) except Exception: self.popen.kill() b_outs, errs = self.popen.communicate() outs = b_outs.decode(encoding=self.coding) return outs, errs @staticmethod def _where(filename, dirs=None, env="PATH"): """Find file in current dir, in deep_lookup cache or in system path""" if dirs is None: dirs = [] if not isinstance(dirs, list): dirs = [dirs] if glob(filename): return filename paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs try: return next(os.path.normpath(match) for path in paths for match in glob(os.path.join(path, filename)) if match) except (StopIteration, RuntimeError): raise IOError("File not found: %s" % filename) if __name__ == '__main__': # Example: with PowerShell('GBK') as ps: outs, errs = ps.run(r'Get-ChildItem G:\test1 -recurse|?{$_.Name -like "test*"}|select Name') #print('error:', os.linesep, errs) #print('output:', os.linesep, outs) print(outs)
这篇关于python 调用 powershell的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器
- 2024-11-16四种数据科学Web界面框架快速对比:Rio、Reflex、Streamlit和Plotly Dash
- 2024-11-14获取参数学习:Python编程入门教程
- 2024-11-14Python编程基础入门