Method for Python3 to execute Linux Bash command
- 2021-07-16 02:39:04
- OfStack
Python still supports system calls and popen () functions to execute linux bash commands, just like C + + used to execute Linux Bash commands.
Method 1: system call
# Only in 1 Sub-terminals run system commands, but cannot obtain the return information after command execution
import os
os.system('ls')
Method 2: popen () function
import os
os.popen('ls').readlines() # The return value is 1 A list
Method 3: Use module subprocess
import subprocess
subprocess.call('ls') # It can be directly call() Call
'''
# You can also use the subprocess.Popen
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print(line)
'''