zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【说站】Python脚本如何调用外部命令

Python 如何 脚本 调用 外部命令
2023-06-13 09:13:21 时间

Python脚本如何调用外部命令

1、os.system将命令和参数传递给系统的shell。

这很好,因为实际上可以以这种方式一次运行多个命令并设置管道和输入/输出重定向。例如:

os.system("some_command < input_file | another_command > output_file")

2、os.system除了提供类似文件的对象,可以使用它来访问该进程的标准输入/输出。

stream = os.popen("some_command with args")将做同样的事情

3、模块的Popen类subprocess。

这旨在替代os.popen但具有由于如此全面而稍微复杂一些的缺点。

print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()

以上就是Python脚本调用外部命令的方法,希望对大家有所帮助。