使用Python程序写入和读取cmd提示符

时间:2017-12-17 16:02:39

标签: python linux python-3.x prompt

我要做什么才能让Python程序在提示符中写出类似" ls"并读取(保存在.txt文件中)命令的输出?

2 个答案:

答案 0 :(得分:1)

您可以使用max = 6 for x in range(1,max+1): for y in range(1,x+1): print '*', print 模块调用命令:

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()

答案 1 :(得分:0)

Python可用于执行bash和批处理命令(Linux和Windows),使用:

subprocess.check_call([“ls”,“ - l”])