本文共 2466 字,大约阅读时间需要 8 分钟。
# test.pyimport sysimport osimport jsonaa = os.system('ls') # system 只返回是否执行成功,为 0 表示执行成功,其他值表示执行失败print(aa)print("-------------------------")bb = os.popen('ls').read() # 使用 popen 可以获取命令执行的输出结果print(bb)
[root@master python3_learning]# python3 test.pyip-address.py test.py world.py0-------------------------ip-address.pytest.pyworld.py
后面我发现, subprocess.Popen 来获取命令执行结果也还是很不错的,很多项目里边也喜欢用。
subprocess.PIPE:一个可以被用于 Popen 的 stdin 、stdout 和 stderr 3 个参数的特输值,表示需要创建一个新的管道。
subprocess.STDOUT:一个可以被用于 Popen 的 stderr 参数的输出值,表示子程序的标准错误汇合到标准输出。
import subprocessp = subprocess.Popen(["cat", "foo.txt"])result, error = p.communicate()print('result1:', result)p = subprocess.Popen(["cat", "foo.txt"], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)result, error = p.communicate()print('result2:', result)p = subprocess.Popen("cat foo.txt", stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)result, error = p.communicate()print('result3:', result)p = subprocess.Popen(["echo", "$PATH"], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)result, error = p.communicate()print('result4:', result)p = subprocess.Popen(["echo", "$PATH"], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)result, error = p.communicate()print('result5:', result)p = subprocess.Popen("echo $PATH", stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)result, error = p.communicate()print('result6:', result)
[root@master python3_learning]# python3 test.pyThis is testhedfllo worldresult1: Noneresult2: b'This is test\nhedfllo world\n'result3: b'This is test\nhedfllo world\n'result4: b'$PATH\n'result5: b'\n'result6: b'/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/.dotnet/tools:/root/lkp-tests/sbin:/root/lkp-tests/bin:/root/lkp-tests/sbin:/root/lkp-tests/bin:/root/.dotnet/tools:/root/lkp-tests/sbin:/root/lkp-tests/bin:/root/lkp-tests/sbin:/root/lkp-tests/bin:/root/.dotnet/tools:/root/lkp-tests/sbin:/root/lkp-tests/bin:/root/lkp-tests/sbin:/root/lkp-tests/bin:/root/.dotnet/tools:/root/lkp-tests/sbin:/root/lkp-tests/bin:/root/lkp-tests/sbin:/root/lkp-tests/bin\n'
# test.rbaa = system('ls') # system 只返回是否执行成功,为 true 表示执行成功,其他值表示执行失败puts aaputs '-----------------------'bb = %x(ls) # 使用 %x 可以获取命令执行的输出结果puts bb
[root@master ruby_learning]# ruby test.rbtest.rb test.txt world.rbtrue-----------------------test.rbtest.txtworld.rb
转载地址:http://injqi.baihongyu.com/