Running External Commands in Python
When working with Python, there may be instances where you need to execute an external program or call a system command as if you were typing it directly in a shell or command prompt. To achieve this, Python provides several methods, including subprocess and os.system.
Using subprocess.run
The recommended and preferred method is to use subprocess.run. It is versatile, safe, and offers more control compared to other options. Here's an example:
import subprocess subprocess.run(["ls", "-l"])
Alternative Method: os.system
Another common approach is to use os.system. However, it is generally unsafe and discouraged as it lacks proper handling of spaces and special characters. Moreover, subprocess.run is more flexible and provides additional capabilities.
Using subprocess.call (Python 3.4 and Earlier)
Prior to Python 3.4, subprocess.call should be used instead of subprocess.run:
subprocess.call(["ls", "-l"])
Safety Considerations
It is essential to use caution when calling external commands within Python. Avoid using os.system if any part of the command comes from external sources or contains potentially malicious characters. Always prefer subprocess.run or subprocess.call, as they provide more control and security features.
The above is the detailed content of How Can I Safely Run External Commands in Python?. For more information, please follow other related articles on the PHP Chinese website!