subprocess库用于在控制台中调用子进程,可以模拟控制台命令输入输出。
subprocess.run
如果只是简单调用运行第三方程序的话,使用subprocess.run最为简单。
下面以调用ping命令为例
# 直接在控制台输出 但由于编码问题中文为乱码
subprocess.run(['ping', 'baidu.com'])
subprocess.run('ping baidu.com', shell=True)
# 通过stdout来获取输出
p = subprocess.run(['ping', 'baidu.com'], stdout=subprocess.PIPE)
print(p.stdout.decode('gbk'))
subprocess.Popen
下面以下面这个相加函数为例,利用subprocess.Popen来调用它
#!/usr/bin/env python
# -*- coding: utf-8 -*-
n = int(input())
nums = []
while n > 0:
a, b = list(map(int, input().strip().split()))
nums.append([a, b])
n -= 1
for a, b in nums:
print(f'{a}+{b}={a + b}')
仿照牛客网上测试程序的流程来进行输入输出,注意stdin的用法
def test(pyfile, datafile):
p = subprocess.Popen(['python.exe', pyfile], stdin=subprocess.PIPE)
with open(datafile) as f:
line = f.readline()
print('..........输入..........')
while line:
print(line.strip())
p.stdin.write(line.encode())
line = f.readline()
p.stdin.close()
print('..........输出..........')
p.wait(2000)
test('add.py', 'data.txt')
# ..........输入..........
# 3
# 1 2
# 5 6
# 7 8
# ..........输出..........
# 1+2=3
# 5+6=11
# 7+8=15
如果有多个测试用例,可以在输入数据时用一个标志符#进行分割
def tests(pyfile, datafile):
with open(datafile) as f:
line = f.readline()
n = 0
while line.strip().startswith('#'):
n += 1
p = subprocess.Popen(['python.exe', pyfile], stdin=subprocess.PIPE)
line = f.readline()
print(f'..........案例[{n}]输入..........')
while line:
print(line.strip())
p.stdin.write(line.encode())
line = f.readline()
if line.strip().startswith('#'):
break
p.stdin.close()
print(f'..........案例[{n}]输出..........')
p.wait()
tests('add.py', 'data.txt')
# ..........案例[1]输入..........
# 3
# 1 2
# 5 6
# 7 8
# ..........案例[1]输出..........
# 1+2=3
# 5+6=11
# 7+8=15
# ..........案例[2]输入..........
# 2
# 1 2
# 5 6
# 7 8
# ..........案例[2]输出..........
# 1+2=3
# 5+6=11
参考
https://www.runoob.com/w3cnote/python3-subprocess.html https://docs.python.org/zh-cn/3/library/subprocess.html