python:cmd管道
commands = f"""ssh root@120.7x.254.99 -p2483 cd /data/wwwroot/csjs2_client_dev git pull ssh://git@172.16.x.161x:2483/data/repos/csjs2_client_dev.git """ import subprocess def subprocess_popen(commands,stdout=subprocess.PIPE, stderr=subprocess.STDOUT): current_process = subprocess.Popen(commands, stdout=stdout, stderr=stderr) standoutput, standerr = current_process.communicate() current_process.wait() current_process.kill() print(standoutput) return standoutput subprocess_popen(commands)
备注:commands写的时候第一行 一定要有 否则按照空行 会报错
最新版
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import subprocess def subprocess_popen(**kwargs): """ 传参:args命令 和 cwd目录 """ error_str = "error" # 传过来是啥就是啥 default_kwargs = { "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, } default_kwargs.update(kwargs) popen_obj = subprocess.Popen(**default_kwargs) stderr_bytes = popen_obj.stderr.read() stdout_bytes = popen_obj.stdout.read() stdout_str = stdout_bytes.decode('utf8') stderr_str = stderr_bytes.decode('utf8') print(f"stdout_str:{stdout_str}") print(f"stderr_str:{stderr_str}") ############ 处理结果 is_error = False # 判断 if stderr_str.lower().__contains__(error_str) or stderr_str: is_error = True if stderr_str.lower().__contains__(error_str): is_error = True #返回格式 response_data = { "stdout_str":stdout_str, "stderr_str":stderr_str, "error":is_error,# 这个值是True或者False,显示的是带error的那个输出 } return response_data res = subprocess_popen(args="ls",cwd="/root") print(f"res:\n{res}")
-----------------------------------------------------------------------------------------------------------------------------------------