Python
os.system 、 os.popen
# test.py
import sys
import os
import json
aa = os.system('ls') # system 只返回是否执行成功,为 0 表示执行成功,其他值表示执行失败
print(aa)
print("-------------------------")
bb = os.popen('ls').read() # 使用 popen 可以获取命令执行的输出结果
print(bb)
[root@master python3_learning]# python3 test.py
ip-address.py test.py world.py
0
-------------------------
ip-address.py
test.py
world.py
subprocess.Popen
Later, I found that subprocess.Popen is still very good to obtain command execution results, and I like to use it in many projects.
subprocess.PIPE: A special input value that can be used for the three parameters of Popen, stdin, stdout, and stderr, indicating that a new pipe needs to be created.
subprocess.STDOUT: An output value that can be used for the stderr parameter of Popen, indicating that the standard error of the subroutine is converged to the standard output.
import subprocess
p = subprocess.Popen(["cat", "foo.txt"])
result, error = p.communicate()
print('result:', result)
p = subprocess.Popen(["cat", "foo.txt"], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
result, error = p.communicate()
print('result:', result)
p = subprocess.Popen("cat fo.txt", stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
result, error = p.communicate()
print('result:', result)
[root@master python3_learning]# python3 test.py
This is test
hello world
result: None
result: b'This is test\nhello world\n'
result: b'cat: fo.txt: No such file or directory\n'
Ruby
# test.rb
aa = system('ls') # system 只返回是否执行成功,为 true 表示执行成功,其他值表示执行失败
puts aa
puts '-----------------------'
bb = %x(ls) # 使用 %x 可以获取命令执行的输出结果
puts bb
[root@master ruby_learning]# ruby test.rb
test.rb test.txt world.rb
true
-----------------------
test.rb
test.txt
world.rb