(1) os.system
# 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息
system(command) -> exit_status
Execute the command (a string) in a subshell.
# 如果再命令行下执行,结果直接打印出来
1 >>> os.system(‘ls‘) 2 3 04101419778.CHM bash document media py-django video 4 5 11.wmv books downloads Pictures python 6 7 all-20061022 Desktop Examples project tools
(2) os.popen
# 该方法不但执行命令还返回执行后的信息对象
popen(command [, mode=‘r‘ [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.
例如:
1 >>>tmp = os.popen(‘ls *.py‘).readlines() 2 3 >>>tmp 4 5 Out[]: 6 7 [‘dump_db_pickle.py ‘, 8 9 ‘dump_db_pickle_recs.py ‘, 10 11 ‘dump_db_shelve.py ‘, 12 13 ‘initdata.py ‘, 14 15 ‘__init__.py ‘, 16 17 ‘make_db_pickle.py ‘, 18 19 ‘make_db_pickle_recs.py ‘, 20 21 ‘make_db_shelve.py ‘, 22 23 ‘peopleinteract_query.py ‘, 24 25 ‘reader.py ‘, 26 27 ‘testargv.py ‘, 28 29 ‘teststreams.py ‘, 30 31 ‘update_db_pickle.py ‘, 32 33 ‘writer.py ‘]
好处在于:将返回的结果赋于一变量,便于程序的处理。
时间: 2024-12-29 06:54:38