Python进程和线程

Table of Contents

1. 概念

2. 环境变量

3. 进程

3.1 system()创建进程

3.2 exec()创建进程

3.3 exit()终止进程

3.4 os.abort()终止进程

4. subprocess

4.1subProcess模块管理进程

4.2 subprocess调用外部命令

5. 进程间的信号机制

6. 线程

6.1 _thread模块

6.2 threading.Thread


1. 概念

2. 环境变量

import os

#不换行输出变量
path = os.environ.get("PATH")
print(path)

#换行输出变量
for key in os.environ.keys():
    print(key, '\t', os.environ[key])
C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
C:\Python\Python38\Scripts\;C:\Python\Python38\;C:\Python\Python37\Scripts\;C:\Python\Python37\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\CMake\bin;C:\Program Files\Git\cmd;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;D:\Tcl\bin;C:\Python\Python38\Scripts\;C:\Python\Python38\;C:\Python\Python37\Scripts\;C:\Python\Python37\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\CMake\bin;C:\Program Files\Git\cmd;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;d:\Program Files\Docker Toolbox;d:\Program Files\JetBrains\PyCharm 2018.3.5\bin;;C:\Python\Python37;
ALLUSERSPROFILE 	 C:\ProgramData
APPDATA 	 C:\Users\nxbb\AppData\Roaming
COMMONPROGRAMFILES 	 C:\Program Files\Common Files
COMMONPROGRAMFILES(X86) 	 C:\Program Files (x86)\Common Files
COMMONPROGRAMW6432 	 C:\Program Files\Common Files
COMPUTERNAME 	 NXBB-PC
COMSPEC 	 C:\Windows\system32\cmd.exe
DOCKER_TOOLBOX_INSTALL_PATH 	 d:\Program Files\Docker Toolbox
FP_NO_HOST_CHECK 	 NO
HOMEDRIVE 	 C:
HOMEPATH 	 \Users\nxbb
LOCALAPPDATA 	 C:\Users\nxbb\AppData\Local
LOGONSERVER 	 \\NXBB-PC
NUMBER_OF_PROCESSORS 	 4
OS 	 Windows_NT
PATH 	 C:\Python\Python38\Scripts\;C:\Python\Python38\;C:\Python\Python37\Scripts\;C:\Python\Python37\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\CMake\bin;C:\Program Files\Git\cmd;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;D:\Tcl\bin;C:\Python\Python38\Scripts\;C:\Python\Python38\;C:\Python\Python37\Scripts\;C:\Python\Python37\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\CMake\bin;C:\Program Files\Git\cmd;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;d:\Program Files\Docker Toolbox;d:\Program Files\JetBrains\PyCharm 2018.3.5\bin;;C:\Python\Python37;
PATHEXT 	 .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW
PROCESSOR_ARCHITECTURE 	 AMD64
PROCESSOR_IDENTIFIER 	 Intel64 Family 6 Model 58 Stepping 9, GenuineIntel
PROCESSOR_LEVEL 	 6
PROCESSOR_REVISION 	 3a09
PROGRAMDATA 	 C:\ProgramData
PROGRAMFILES 	 C:\Program Files
PROGRAMFILES(X86) 	 C:\Program Files (x86)
PROGRAMW6432 	 C:\Program Files
PSMODULEPATH 	 C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
PUBLIC 	 C:\Users\Public
PYCHARM 	 d:\Program Files\JetBrains\PyCharm 2018.3.5\bin;
PYCHARM_HOSTED 	 1
PYCHARM_MATPLOTLIB_PORT 	 30584
PYTHONIOENCODING 	 UTF-8
PYTHONPATH 	 E:\python\python project;C:\Program Files\JetBrains\PyCharm 2018.3.5\helpers\pycharm_matplotlib_backend
PYTHONUNBUFFERED 	 1
SESSIONNAME 	 Console
SYSTEMDRIVE 	 C:
SYSTEMROOT 	 C:\Windows
TEMP 	 C:\Users\nxbb\AppData\Local\Temp
TMP 	 C:\Users\nxbb\AppData\Local\Temp
USERDOMAIN 	 nxbb-PC
USERNAME 	 nxbb
USERPROFILE 	 C:\Users\nxbb
VBOX_MSI_INSTALL_PATH 	 C:\Program Files\Oracle\VirtualBox\
VISUALGDB_DIR 	 C:\Program Files (x86)\Sysprogs\VisualGDB\
VS100COMNTOOLS 	 D:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\
VS140COMNTOOLS 	 D:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\
WINDIR 	 C:\Windows

3. 进程

3.1 system()创建进程

import  os

#system创建一个进程,并输出其命令信息
print(os.system("dir"))
C:\Python\Python38\python.exe "E:/python/python project/myUrl.py"
 Volume in drive E has no label.
 Volume Serial Number is DA28-2548

 Directory of E:\python\python project

2020/01/15  22:59    <DIR>          .
2020/01/15  22:59    <DIR>          ..
2020/01/15  22:59    <DIR>          .idea
2020/01/15  22:55            15,997 hello world.py
2019/12/31  23:59                84 helloworld.txt
2019/12/29  22:13               398 myModule.py
2020/01/15  22:59                37 myUrl.py
2020/01/15  22:56    <DIR>          SQLITE
2020/01/13  22:30    <DIR>          venv
2019/12/29  22:24    <DIR>          __pycache__
               4 File(s)         16,516 bytes
               6 Dir(s)  39,953,666,048 bytes free
0

Process finished with exit code 0

3.2 exec()创建进程

import os

#启动一个记事本
notepad = "c:\\windows\\notepad.exe"
os.execl(notepad, "notepad.exe")

3.3 exit()终止进程

import  sys

#try部分异常时将执行except捕获
try:
    filename = sys.argv[1]
    print(filename)
except:
    print("Usage:", sys.argv[0], "filename")
    sys.exit(1)
C:\Python\Python38\python.exe "E:/python/python project/myUrl.py"
Usage: E:/python/python project/myUrl.py filename

Process finished with exit code 1

3.4 os.abort()终止进程

import  os
import sys

#try部分异常时将执行except捕获
try:
    filename = sys.argv[1]
    print(filename)
except:
    print("Usage:", sys.argv[0], "filename")
    os.abort(0)
C:\Python\Python38\python.exe "E:/python/python project/myUrl.py"
Traceback (most recent call last):
  File "E:/python/python project/myUrl.py", line 6, in <module>
    filename = sys.argv[1]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:/python/python project/myUrl.py", line 10, in <module>
    os.abort(0)
TypeError: abort() takes no arguments (1 given)
Usage: E:/python/python project/myUrl.py filename

Process finished with exit code 1

4. subprocess

4.1subProcess模块管理进程

import subprocess

ping = subprocess.Popen(args="ping -n 4 www.baidu.com", shell=True)
print(ping.pid)
print(ping.returncode)

 

上面没有加等待子进程结束,导致ping的命令信息在Pycharm控制台上没有看到,现在增加等待子进程结束可以正常显示了

import subprocess

ping = subprocess.Popen(args="ping -n 4 www.baidu.com", shell=True)
#增加子进程等待执行结束
ping.wait()
print(ping.pid)
print(ping.returncode)
C:\Python\Python38\python.exe "E:/python/python project/myUrl.py"

Pinging www.a.shifen.com [163.177.151.110] with 32 bytes of data:
Reply from 163.177.151.110: bytes=32 time=16ms TTL=47
Reply from 163.177.151.110: bytes=32 time=17ms TTL=47
Reply from 163.177.151.110: bytes=32 time=18ms TTL=47
Reply from 163.177.151.110: bytes=32 time=17ms TTL=47

Ping statistics for 163.177.151.110:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 16ms, Maximum = 18ms, Average = 17ms
2860
0

Process finished with exit code 0

由于子进程的调试信息无法输出,可以通过以下方式进行输出到当前控制台

import subprocess

ping = subprocess.Popen(args="ping -n 4 www.baidu.com", shell=True)

#增加子进程等待执行结束
ping.wait()
#读取进程的输出信息
print(ping.stdout.read())
print(ping.pid)
print(ping.returncode)
C:\Python\Python38\python.exe "E:/python/python project/myUrl.py"

Pinging www.a.shifen.com [163.177.151.110] with 32 bytes of data:
Reply from 163.177.151.110: bytes=32 time=17ms TTL=47
Reply from 163.177.151.110: bytes=32 time=17ms TTL=47
Reply from 163.177.151.110: bytes=32 time=22ms TTL=47
Reply from 163.177.151.110: bytes=32 time=23ms TTL=47

Ping statistics for 163.177.151.110:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 17ms, Maximum = 23ms, Average = 19ms
Traceback (most recent call last):
  File "E:/python/python project/myUrl.py", line 8, in <module>
    print(ping.stdout.read())
AttributeError: 'NoneType' object has no attribute 'read'

Process finished with exit code 1

4.2 subprocess调用外部命令

 这条命令与os.sytem是相同的

import  subprocess

subprocess.call("dir", shell=True)
C:\Python\Python38\python.exe "E:/python/python project/myUrl.py"
 Volume in drive E has no label.
 Volume Serial Number is DA28-2548

 Directory of E:\python\python project

2020/01/15  23:53    <DIR>          .
2020/01/15  23:53    <DIR>          ..
2020/01/15  23:53    <DIR>          .idea
2020/01/15  22:55            15,997 hello world.py
2019/12/31  23:59                84 helloworld.txt
2019/12/29  22:13               398 myModule.py
2020/01/15  23:53                56 myUrl.py
2020/01/15  22:56    <DIR>          SQLITE
2020/01/13  22:30    <DIR>          venv
2019/12/29  22:24    <DIR>          __pycache__
               4 File(s)         16,535 bytes
               6 Dir(s)  39,953,141,760 bytes free

Process finished with exit code 0

5. 进程间的信号机制

import  subprocess
import signal

def signal_handle(signum, fram):
    print("signal handle: signum=%d" % signum)

signal.signal(signal.SIGINT, signal_handle)

ping = subprocess.Popen(args="ping -n 10 www.baidu.com", shell=True)
ping.wait()
print(ping.pid)
print(ping.returncode)

6. 线程

6.1 _thread模块

import _thread
import time

def worker(index, create_time):
    #time.sleep(1)
    print((time.time()-create_time), index)
    print("Thread %d exit..." % (index))

for index in range(5):
    time.sleep(1)
    _thread.start_new_thread(worker, (index, time.time()))

time.sleep(3)
print("Main thread exit...")
C:\Python\Python38\python.exe "E:/python/python project/myThread.py"
0.0010001659393310547 0
Thread 0 exit...
0.0 1
Thread 1 exit...
0.0010001659393310547 2
Thread 2 exit...
0.0 3
Thread 3 exit...
0.0 4
Thread 4 exit...
Main thread exit...

Process finished with exit code 0

6.2 threading.Thread

import threading
import time

class ThreadSkeleton(threading.Thread):
    def __init__(self, index, create_time): #线程构造函数
        threading.Thread.__init__(self)
        self.index = index
        self.create_time = create_time

    def run(self):
        time.sleep(1)
        print((time.time() - self.create_time), "\t", index)
        print("Thread %d exit..." % (self.index))

for index in range(5):
    thread = ThreadSkeleton(index, time.time())
    thread.start()

time.sleep(5)
print("*********************")

 

C:\Python\Python38\python.exe "E:/python/python project/myThread.py"
1.0000569820404053 	 4
Thread 0 exit...
1.0000569820404053 	 41.0000569820404053 	
Thread 1 exit...
1.0000569820404053 	 4
Thread 3 exit...
 4
Thread 2 exit...
1.0010571479797363 	 4
Thread 4 exit...
*********************

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值