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?
Asked
Active
Viewed 65 times
-2
-
I'm using linux and Python 3.6 – Luigi Bernardi Dec 17 '17 at 16:03
-
1Possible duplicate of [Calling an external command in Python](https://stackoverflow.com/questions/89228/calling-an-external-command-in-python) – Jerfov2 Dec 17 '17 at 16:05
2 Answers
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,845
- 1
- 12
- 25
0
Python can be used to execute bash and batch commands (Linux & Windows), by making use of:
subprocess.check_call(["ls", "-l"])