Python Forum

Full Version: Python syntax in Linux
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am currently learning Python in school and have truly enjoyed it. This week we are to working with subprocess. we are to run commands and take screenshots, but the commands they have given us are all for Windows and I run Linux. out of the 15 commands I have figured out all except for one.

The question says:
Use subprocess.Popen to execute the Windows dir command and have its output placed in a text file named pythonOut.txt Hint: The argument for Popen in this case will be subprocess.Popen('C:\\windows\\system32\\cmd.exe "/c dir C:\\ >> C:\\pythonOut.txt"')

I have been racking my brain to find how to do this. I have found that subprocess.Popen(['ls', '-a']) will pull a directory and display it on the screen but how do I output that into a file using a single command line as the Windows example above?

Thank you for your help,

St0rmcr0w
You need to use subprocess.PIPE for stdout or use a file-like object.
If you open a file, you've a file like object. Popen expects the write method on the stdout/stderr object.


from pathlib import Path
import subprocess

def run_stdout_save(cmd, file_append):
    """
    Append stdout of cmd to a file.
    This is a blocking function
    """
    # open the file in append raw bytes mode
    # this will prevent encoding errors
    with open(file_append, "ab") as fd:

        # suppress window
        startup_info = subprocess.STARTUPINFO()
        startup_info.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        proc = subprocess.Popen(cmd, stdout=fd, startupinfo=startup_info)
        # wait until it's finished
        proc.wait()


# using pathlib to create the paths
stdout_file = Path.home() / "Desktop/proc_stdout.txt"

cmd = "C:\\windows\\system32\\cmd.exe"
# each argument is a str element in the list.
run_stdout_save([cmd, "/c",  "dir", "C:\\"], stdout_file)
(Jul-29-2021, 12:16 PM)St0rmcr0w Wrote: [ -> ]I have found that subprocess.Popen(['ls', '-a']) will pull a directory and display it on the screen but how do I output that into a file using a single command line as the Windows example above?
I would do it like this on Linux.
So run() that should be used in most cases got new capture_output parameter in Python 3.7>.
import subprocess

ls_files = subprocess.run(["ls", "-l", "/home/tom"], capture_output=True)
print(ls_files.stdout.decode())
with open('ls_out.txt', 'w') as f:
    f.write(ls_files.stdout.decode())
subprocess dok Wrote:The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle.
For more advanced use cases, the underlying Popen interface can be used directly.