python 执行shell
时间: 2023-04-28 19:01:33 浏览: 49
Python 可以通过 subprocess 模块执行 shell 命令。具体方法是使用 subprocess.run() 函数,将 shell 命令作为参数传入即可。例如:
import subprocess
result = subprocess.run('ls -l', shell=True, stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))
上面的代码会执行 ls -l 命令,并将结果输出到控制台。其中,shell=True 表示使用 shell 执行命令,stdout=subprocess.PIPE 表示将命令输出保存到变量 result 中。最后,使用 decode() 方法将输出转换为字符串。
相关问题
python 调用shell
Python可以通过subprocess模块调用shell命令。可以使用subprocess.call()函数来执行shell命令,也可以使用subprocess.Popen()函数来执行shell命令并获取输出。例如:
使用subprocess.call()函数:
import subprocess
subprocess.call('ls -l', shell=True)
使用subprocess.Popen()函数:
import subprocess
p = subprocess.Popen('ls -l', shell=True, stdout=subprocess.PIPE)
output, err = p.communicate()
print(output.decode('utf-8'))
python调用shell
Python可以通过subprocess模块调用shell命令。可以使用subprocess.call()函数来执行shell命令,也可以使用subprocess.Popen()函数来创建一个新的进程并执行shell命令。在调用shell命令时,需要注意安全性问题,避免使用不安全的命令或参数。