Python Subprocess Accessing Operating System
It is often useful to be able to run other programs from within a script and the subprocess module is the preferred tool for this.The module also have several convenience functions that you can use when a simpler approach is preferred.The documentation describe how to use all of these features;
The most basic use of the subprocess us to call an external OS command and simply it to run its course.The output is usually displayed on screen or stored in a data file somewhere.The easiest way to see how it works is to try it out.
TRY IT OUT
HOW IT WORK
After importing subprocess with the alias sub in the first line, you called sub.call() for the first time, with an argument of ['ls'] on Mac/Linux machine.The only thing returned by call() is the operating system return code,which tells if the program completed successfully or not but it does not help you to interact with the data in any way. You than sub.call() second time but this time you redirected stdout to an new file called ls.txt. Now you can use this ls.txt file from python code and read line / print it on the screen using regular python
The most basic use of the subprocess us to call an external OS command and simply it to run its course.The output is usually displayed on screen or stored in a data file somewhere.The easiest way to see how it works is to try it out.
TRY IT OUT
- Create a test directory called root and populate it with a few text files.
- Change into your root folder and start the python interpreter.
- Type the following code the the >>> prompt
(base) Apples-MacBook-Pro:test-project apple$ mkdir root (base) Apples-MacBook-Pro:test-project apple$ cd root/ (base) Apples-MacBook-Pro:root apple$ touch fileA.txt (base) Apples-MacBook-Pro:root apple$ touch fileB.txt (base) Apples-MacBook-Pro:root apple$ python Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import subprocess as sub >>> sub.call(['ls'], stdout=open('ls.txt','w')) 0 >>> sub.call(['more','ls.txt']) fileA.txt fileB.txt ls.txt 0 >>> for line in open('ls.txt'):print(line) ... fileA.txt fileB.txt ls.txt
HOW IT WORK
After importing subprocess with the alias sub in the first line, you called sub.call() for the first time, with an argument of ['ls'] on Mac/Linux machine.The only thing returned by call() is the operating system return code,which tells if the program completed successfully or not but it does not help you to interact with the data in any way. You than sub.call() second time but this time you redirected stdout to an new file called ls.txt. Now you can use this ls.txt file from python code and read line / print it on the screen using regular python
Comments
Post a Comment