AutoFramework/Base/Class/Command.py

48 lines
1.7 KiB
Python
Raw Normal View History

2022-06-27 23:11:22 +08:00
import re,chardet,subprocess
2022-06-29 23:25:57 +08:00
def shell(cmd='', stdout=None, stderr=None, timeout=None):
2022-06-27 23:11:22 +08:00
match stdout:
case 'NULL' | 'Null' | 'null':
stdoutCh = subprocess.DEVNULL
case _:
stdoutCh = subprocess.PIPE
match stderr:
case 'NULL' | 'Null' | 'null':
stderrCh = subprocess.DEVNULL
case _:
stderrCh = subprocess.PIPE
2022-06-29 23:25:57 +08:00
try:
result = subprocess.run(cmd, shell=True, stdout=stdoutCh, stderr=stderrCh, timeout=timeout)
stdoutContent = ''
stderrContent = ''
if result.stdout:
stdoutContent = result.stdout.decode(chardet.detect(result.stdout)["encoding"] or 'UTF-8')
if result.stderr:
stderrContent = result.stderr.decode(chardet.detect(result.stderr)["encoding"] or 'UTF-8')
return {
"code": result.returncode, "stdout": stdoutContent, "stderr": stderrContent
}
except subprocess.TimeoutExpired:
return {
"code": 1,
"stdout": '',
"stderr": 'Execution timeout.'
}
2022-06-27 23:11:22 +08:00
if __name__ == '__main__':
2022-06-29 23:25:57 +08:00
# Example. Normal.
print(shell('ping www.taobao.com'))
# Example. No STDOUT.
print(shell('ping www.taobao.com', stdout='NULL'))
# Example. No STDERR.
print(shell('ping www.taobao.com', stderr='NULL'))
# Example. No STDOUT and STDERR.
print(shell('ping www.taobao.com', stdout='NULL', stderr='NULL'))
# Example. With Timeout.
print(shell('ping www.taobao.com', timeout=3))
# Example. With Timeout Not.
print(shell('ping www.taobao.com', timeout=8))
# Example. Curl.
print(shell('curl "https://www.baidu.com/"'))
# Example. Unknown Command.
print(shell('busybox ls'))