Three ways python calls other scripts, do you know anything else?

Keywords: Python shell

1. Call python scripts with python

#!/usr/local/bin/python3.7
import time
import os 

count = 0
str = ('python b.py')
result1 = os.system(str)
print(result1)
while True:
    count = count + 1
    if count == 8:
      print('this count is:',count) 
      break
    else:
      time.sleep(1)
      print('this count is:',count)   

print('Good Bye')

Another python script, b.py, is as follows:

#!/usr/local/bin/python3.7
print('hello world')

Run result:

[python@master2 while]$ python a.py 
hello world
this count is: 1
this count is: 2
this count is: 3
this count is: 4
this count is: 5
this count is: 6
this count is: 7
this count is: 8
Good Bye

2.python calls the shell method os.system()

'''
//No one answered the question?Xiaobian created a Python learning and communication QQ group: 579817333 
//Find like-minded partners, help each other, and there are good video learning tutorials and PDF e-books in the group!
'''
#!/usr/local/bin/python3.7
import time
import os 

count = 0
n = os.system('sh b.sh')
while True:
    count = count + 1
    if count == 8:
      print('this count is:',count) 
      break
    else:
      time.sleep(1)
      print('this count is:',count)   

print('Good Bye')

The shell script is as follows:

#!/bin/sh
echo "hello world"

Run result:

[python@master2 while]$ python a.py 
hello world
this count is: 1
this count is: 2
this count is: 3
this count is: 4
this count is: 5
this count is: 6
this count is: 7
this count is: 8
Good Bye

3.python calls the shell method os.popen()

'''
//No one answered the question?Xiaobian created a Python learning and communication QQ group: 579817333 
//Find like-minded partners, help each other, and there are good video learning tutorials and PDF e-books in the group!
'''
#!/usr/local/bin/python3.7
import time
import os 

count = 0
n = os.system('sh b.sh')
while True:
    count = count + 1
    if count == 8:
      print('this count is:',count) 
      break
    else:
      time.sleep(1)
      print('this count is:',count)   

print('Good Bye')

Run result:

[python@master2 while]$ python a.py 
<os._wrap_close object at 0x7f7f89377940>
['hello world\n']
this count is: 1
this count is: 2
this count is: 3
this count is: 4
this count is: 5
this count is: 6
this count is: 7
this count is: 8
Good Bye

os.system.popen() opens a pipe and returns the result as a file object that connects the pipe. The file object operates in the same way as open() and the result can be read from the file object.If the execution is successful, the status code is not returned, and if the execution fails, the error information is output to stdout and an empty string is returned.The subprocess module has also officially implemented a more powerful subprocess.Popen() method.

Posted by dksmarte on Mon, 06 Jan 2020 21:56:28 -0800