官方文檔中有關(guān)于subprocess的使用方法
在做網(wǎng)易的一個(gè)編程題嵌巷,錢老板的保險(xiǎn)箱,有一個(gè)可執(zhí)行文件(包含windows刚陡、linux和macOS版本)地址為:http://59.111.13.242/leihuo_2019_guess.zip。每次輸入一個(gè)0-1的浮點(diǎn)數(shù),會(huì)得到一個(gè)輸出翠储。
image
思路:通過(guò)多次直行源代碼來(lái)擬合出這個(gè)函數(shù)的曲線。
因此首先需要獲得數(shù)據(jù)集橡疼,就是獲取多次的輸入輸出值來(lái)進(jìn)行擬合援所。小樣本擬合效果不佳,因此需要多次進(jìn)行密碼的輸入并且獲取其輸出欣除。
import subprocess
def create_grid(commands):
process = subprocess.Popen(
['/Users/xds/Downloads/leihuo_2019_guess(1)/guess_macos'],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
# print(type(commands))
out = process.communicate(commands)
# process.communicate(input= '\n'.join(commands) + '\n')
print(out)
subprocess.PIPE
可被 Popen
的 stdin, stdout 或者 stderr 參數(shù)使用的特殊值, 表示打開(kāi)標(biāo)準(zhǔn)流的管道. 常用于 Popen.communicate()
.
方法1
可以新建一個(gè)文本住拭,然后按行讀取要輸入的參數(shù)
# 打開(kāi)文件
f = open('/Users/xds/Downloads/leihuo_2019_guess(1)/input.txt')
# 連成字符串
input = ''.join(f)
# 轉(zhuǎn)成字節(jié)碼
input = input.encode()
# 將每一行輸入
create_grid(input)
image
方法2
也可以新建一個(gè)numpy數(shù)組,然后處理成字節(jié),輸進(jìn)函數(shù)
# 生成一個(gè)numpy數(shù)組
x2 = np.arange(1,25,0.1)/25
# 拼接成一個(gè)list
a = [''.join(str(i)) for i in x2]
# 用\n連接成字符串滔岳,并轉(zhuǎn)成字節(jié)
b = ('\n'.join(a)).encode()
create_grid(b)
image
image