import os
os.getpid()
657
os.getcwd()
‘/home/sumin/projects/python/IntroducingPython/10. 시스템’
os.getuid()
1000
os.getgid()
1000
10.3.1 프로세스 생성하기(1): subprocess
- 파이썬 표준 라이브러리의 subprocess 모듈로 존재하는 다른프로그램을 시작하거나 멈출 수 있다.
import subprocess ret = subprocess.getoutput('date') ret
‘2018. 03. 05. (월) 17:28:14 KST’
ret = subprocess.getoutput('date -u') ret
‘2018. 03. 05. (월) 08:28:41 UTC’
ret = subprocess.getoutput('date -u | wc') ret
’ 1 6 33’
ret = subprocess.check_output(['date', '-u']) ret
b’2018. 03. 05. (\xec\x9b\x94) 08:30:00 UTC\n’
ret = subprocess.getstatusoutput('date') ret
(0, ‘2018. 03. 05. (월) 17:30:42 KST’)
ret = subprocess.call('date')
ret
0
print(subprocess.call('date -u', shell=True))
0
ret = subprocess.call(['date', '-u'])
ret
0
10.3.2 프로세스 생성하기(2): multiprocessing
import multiprocessing
import os
def do_this(what):
whoami(what)
def whoami(what):
print('Process %s says %s' % (os.getpid(), what))
if __name__ == '__main__':
whoami("I'm the main program")
for n in range(4):
p = multiprocessing.Process(target=do_this, args=("I'm function %s" % n,))
p.start()
Process 657 says I’m the main program Process 855 says I’m function 2 Process 858 says I’m function 3 Process 853 says I’m function 1 Process 851 says I’m function 0
10.3.3 프로세스 죽이기: terminate()
import multiprocessing
import time
import os
def whoami(name):
print("I'm %s, in process %s" % (name, os.getpid()))
def loopy(name):
whoami(name)
start = 1
stop = 100000
for num in range(start, stop):
print("\tNumber %s of %s, Honk!" % (num, stop))
time.sleep(1)
if __name__ == '__main__':
whoami("main")
p = multiprocessing.Process(target=loopy, args=("loopy",))
p.start()
time.sleep(5)
p.terminate()
I’m main, in process 657 I’m loopy, in process 965 Number 1 of 100000, Honk! Number 2 of 100000, Honk! Number 3 of 100000, Honk! Number 4 of 100000, Honk! Number 5 of 100000, Honk!
Comments