In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "Python's methods of executing external commands". In daily operation, I believe many people have doubts about Python's methods of executing external commands. Xiaobian consulted various materials and sorted out simple and easy operation methods. I hope to help you answer the doubts of "Python's methods of executing external commands"! Next, please follow the small series to learn together!
1. system function
The basic call format is as follows:
import os os.system("some_command with args");
The system function passes commands and arguments to the system's Shell. This is great because you can actually run multiple commands at once this way and set up pipes and input/output redirects. For example:
import os os.system("cat command.py | grep -n subprocess > result.txt")
Executing this code generates a result.txt file in the current directory.
Although this is convenient, escape characters (such as spaces) must be handled manually. So doing this simply lets you run the Shell program, not extend the program's functionality.
2. popen function
The basic call format is as follows:
import os stream = os.popen("some_command with args")
The popen function does the same thing as the os.system function, except that popen provides an object for manipulating files and accessing data in files using standard input and output. There are three other variants of the popen function that handle I/O slightly differently. If you pass everything as a string, the command is passed to the Shell program; if you pass it as a list, you don't have to worry about escaping anything. For example:
import os stream = os.popen("cat command.py | grep -n subprocess") print(type(stream)) result = stream.readlines() print(type(result)) print(result)
Executing this code will output the following:
['1:import subprocess\n', '2:subprocess.run(["ls", "-l"])\n', '5:subprocess.call(["ls", "-l"])\n', '8:os.system("cat command.py | grep -n subprocess > result.txt")\n']
As you can see, the readlines method returns the results of the command execution in list form.
3. Popen class
The Popen class of the subprocess module. This class can be used to replace the os.popen function. However, the disadvantage of Popen class is that it is too powerful, so it is slightly more complicated to use. For example:
print(subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read())
This line of code can be used to replace the following:
print(os.popen("echo Hello World").read())
A more complex example of the Popen class is as follows:
import subprocess p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print(line.decode("utf-8").strip()) retval = p.wait()
This code reads all the lines returned by the ls command through the standard output readlines method and outputs them to Console. Finally, use the wait method to wait for the ls command to execute, and finally end the program.
The advantage of the Popen class over the popen function is that all options are grouped together in the Popen class, rather than requiring four different popen functions to do the work.
4. Call function
Call function from subprocess module. Just like the Popen class, it has the same arguments, but the call function only waits for the command to finish executing and provides a return code. For example:
return_code = subprocess.call("echo Hello World", shell=True) print(return_code)
5. run function
If you are using Python 3.5 or later, you can use the new subprocess.run function, which is very similar to the code above, but more flexible and returns a CompletedProcess object after the command completes execution. For example:
import subprocess result = subprocess.run(["ls", "-l"]) print(type(result))
6. C-like function
The os module also provides fork / exec / spawn functions similar to C, but I don't recommend using them directly, for example:
import os print(os.execl('/bin/ls', ' '))
Finally, note that for these methods that execute external commands, you need to pass strings of parameters back to the program after these commands are executed, and sometimes you need to transfer these returned strings. If you can't trust these strings completely, there's a serious security risk. For example, if the user is entering some/any part of a string. If you are unsure, use these methods only with constants. To illustrate this point better, look at the code below.
print(subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read())
Imagine typing "I love your harddisk && rm -rf /," which erases all data on the hard disk. So if you can't trust the user input completely, change the variable user_input to a constant to prevent the user from entering arbitrary input.
At this point, the study of "Python's methods of executing external commands" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un