Executing Programs and System Commands in Python
This question demonstrates how to execute an external command from within a Python script, simulating the functionality of typing the command directly into a shell or command prompt. To achieve this, Python provides several methods.
subprocess.run()
The recommended approach is to utilize the subprocess.run() function. This method takes a list of command arguments as its input and executes the corresponding program.
import subprocess subprocess.run(["ls", "-l"])
os.system()
Another option is to use os.system(), which directly invokes the operating system's command shell. However, this method is considered insecure as it can be exploited if parts of the command originate from external sources or contain special characters.
subprocess.call()
For Python versions 3.4 and earlier, subprocess.call() should be used instead of .run():
subprocess.call(["ls", "-l"])
Advantages of subprocess.run()
Compared to os.system(), subprocess.run() offers greater flexibility and safety. It provides access to stdout, stderr, accurate status codes, and improved error handling.
Therefore, for safe and versatile execution of programs and system commands in Python, subprocess.run() is the preferred method.
The above is the detailed content of How Can I Safely Execute System Commands and Programs in Python?. For more information, please follow other related articles on the PHP Chinese website!