A process is an external program that executes on the operating system. It does something important (unless it does not).
We can invoke subprocess.run
after importing the subprocess
module. Usually we invoke external EXE files. We can specify arguments.
Here we are on Windows and we want to invoke notepad.exe for an unknown reason. We can simply pass the string
"notepad.exe" to subprocess.run
.
string
literals with the "r" prefix.import subprocess # Launch windows application. subprocess.run("notepad.exe") # Launch windows application with argument. # ... The window may be below the previous one. subprocess.run(r"notepad.exe C:\programs\file.txt")
We can use external programs, like the 7-Zip compression software, to compress files. We invoke an external binary file.
subprocess
module to call the executable. The subprocess.call
method is an easy to way to invoke an external program.string
is used to build up the command line. This is the uncompressed file. You will need to change this.import subprocess exe = "C:\\7za.exe" source = "C:\profiles\strong.bin" target = "C:\profiles\strong.7z" subprocess.call(exe + " a -t7z \"" + target + "\" \"" + source + "\" -mx=9")7-Zip (A) 9.07 beta Copyright (c) 1999-2009 Igor Pavlov 2009-08-29 Scanning Creating archive C:\profiles\strong.7z Compressing strong.bin Everything is Ok
This example uses subprocess
to launch a more powerful compressor, PAQ. A PAQ executable is available in downloadable archives on the Internet.
import subprocess # This program handles compressed (fp8) files and non-compressed ones. # ... It decompresses or compresses. exe = r"C:\fp8_v2.exe" source = r"C:\profiles\file.bin" subprocess.call(exe + " " + source)Creating archive C:\profiles\file.bin.fp8 with 1 file(s)... File list (18 bytes) Compressed from 18 to 22 bytes. 1/1 Filename: C:/profiles/file.bin (3836648 bytes) Block segmentation: 0 | default | 28016 bytes [0 - 28015] 1 | jpeg | 8917 bytes [28016 - 36932] 2 | default | 3799715 bytes [36933 - 3836647] Compressed from 3836648 to 114930 bytes. Total 3836648 bytes compressed to 114958 bytes. Time 44.26 sec, used 180892539 bytes of memory Close this window or press ENTER to continue...
Python has support for launching external processes at the level of the operating system. This is commonly needed, and commonly useful.