为了使Python程序在提示符中写入“ls”并读取(保存在.txt文件中)命令的输出,我该怎么做?
您可以使用subprocess
模块调用命令:
import subprocess
# Call the command with the subprocess module
# Be sure to change the path to the path you want to list
proc = subprocess.Popen(["ls", "/your/path/here"], stdout=subprocess.PIPE)
# Read stdout from the process
result = proc.stdout.read().decode()
# Be safe and close the stdout.
proc.stdout.close()
# Write the results to a file.
with open("newfile.txt", "w") as f:
f.write(result)
请注意..如果您只想列出目录,os
模块有一个listdir()
方法:
import os
with open("newfile.txt", "w") as f:
for filename in os.listdir("/your/path/here"):
f.write(filename)
Python可用于执行bash和批处理命令(Linux和Windows),方法是:
subprocess.check_call([“ls”,“ - l”])