-2

What have I to do in order to make a Python program write in the prompt something like "ls" and read (save in a .txt file) the output of the command?

Eryk Sun
  • 29,588
  • 3
  • 76
  • 95

2 Answers2

1

You can call a command with the subprocess module:

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)

Do note though.. If you just want to list a directory, the os module has a listdir() method:

import os

with open("newfile.txt", "w") as f:
    for filename in os.listdir("/your/path/here"):
        f.write(filename)
Jebby
  • 1,617
  • 1
  • 10
  • 24
0

Python can be used to execute bash and batch commands (Linux & Windows), by making use of:

subprocess.check_call(["ls", "-l"])