os.system()
只返回命令的退出状态(而不是
STDOUT
). 你应该使用
subprocess
模块,尤其是
subprocess.Popen
代码:
import subprocess
import sys
def call_command(command):
"""
Call a command the STDOUT
:param command: The related command
:return: STDOUT as string
"""
result1 = subprocess.Popen(
command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True
)
# Get the STDOUT and STDERR descriptors of the command.
std_out, std_err = result1.communicate()
return std_out
# Find files in test1 folder.
find_result = call_command("find test1/ -type f")
for one_find in find_result.split("\n"):
if one_find:
# The result of cat command will be in "cat_result" variable.
cat_result = call_command("cat {}".format(one_find))
print(cat_result)
# You can write the result directly to STDOUT with the following line.
# sys.stdout.write("\n".join(call_command("cat {}".format(one_find))))
内容
test1
>>> ll test1/
total 8
drwxrwxr-x 2 user grp 4096 Jul 8 14:18 ./
drwxrwxr-x 18 user grp 4096 Jul 8 14:33 ../
-rw-rw-r-- 1 user grp 29 Jul 8 14:18 test_file.txt
内容
test_file.txt
:
>>> cat test1/test_file.txt
Contents of test_file.txt file
代码输出:
>>> python3 test.py
Contents of test_file.txt file.