def plot(self): self.is_running = False pwd_path = os.path.abspath(os.path.join(os.getcwd(), "..")) script_path = os.path.join(pwd_path, 'callisto-test-tool\\algo_galileo_2e235eb933c9_deg90\\An_test') folder_path = os.path.join(pwd_path, 'callisto-test-tool\\source\\Test_Source_Data') os.chdir(script_path) os.system('powershell -Command "./csv_output.sh {0}"'.format(folder_path)) 怎么检测该段程序中powershell是否运行完毕

时间: 2024-02-13 19:03:30 浏览: 28
要检测该段程序中 `powershell` 是否运行完毕,可以使用 Python 的 `subprocess` 模块来代替 `os.system` 函数来运行 `powershell`,并使用 `communicate()` 方法来等待 `powershell` 进程结束。例如: ``` import subprocess def plot(self): self.is_running = False pwd_path = os.path.abspath(os.path.join(os.getcwd(), "..")) script_path = os.path.join(pwd_path, 'callisto-test-tool\\algo_galileo_2e235eb933c9_deg90\\An_test') folder_path = os.path.join(pwd_path, 'callisto-test-tool\\source\\Test_Source_Data') os.chdir(script_path) cmd = 'powershell -Command "./csv_output.sh {0}"'.format(folder_path) process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() # 等待进程结束 if process.returncode == 0: print('程序执行成功!') else: print('程序执行失败!') ``` 这样就可以在程序执行完成后得到 `powershell` 进程的返回值,并根据返回值来判断程序是否执行成功。如果返回值为 0,则表示程序执行成功,否则表示程序执行失败。

相关推荐

import tkinter as tk import pandas as pd import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import os class ExcelPlotter(tk.Frame): def init(self, master=None): super().init(master) self.master = master self.master.title("图方便") self.file_label = tk.Label(master=self, text="Excel File Path:") self.file_label.grid(row=0, column=0, sticky="w") self.file_entry = tk.Entry(master=self) self.file_entry.grid(row=0, column=1, columnspan=2, sticky="we") self.file_button = tk.Button(master=self, text="Open", command=self.open_file) self.file_button.grid(row=0, column=3, sticky="e") self.plot_button = tk.Button(master=self, text="Plot", command=self.plot_data) self.plot_button.grid(row=1, column=2, sticky="we") self.name_label = tk.Label(master=self, text="Out Image Name:") self.name_label.grid(row=2, column=0, sticky="w") self.name_entry = tk.Entry(master=self) self.name_entry.grid(row=2, column=1, columnspan=2, sticky="we") self.save_button = tk.Button(master=self, text="Save", command=self.save_image) self.save_button.grid(row=2, column=3, sticky="e") self.figure = plt.figure(figsize=(5, 4), dpi=150) self.canvas = FigureCanvasTkAgg(self.figure, master=self) self.canvas.get_tk_widget().grid(row=4, column=0, columnspan=4, sticky="we") self.pack() def open_file(self): file_path = tk.filedialog.askopenfilename(filetypes=[("Excel Files", "*.xls")]) self.file_entry.delete(0, tk.END) self.file_entry.insert(tk.END, file_path) def plot_data(self): file_path = self.file_entry.get() if os.path.exists(file_path): data = pd.read_excel(file_path) plt.plot(data['波长(nm)'], data['吸光度'], 'k') plt.xlim(300, 1000) plt.xlabel('Wavelength(nm)', fontsize=16) plt.ylabel('Abs.', fontsize=16) plt.gcf().subplots_adjust(left=0.13, top=0.91, bottom=0.16) plt.savefig('Last Fig', dpi=1000) plt.show() def save_image(self): if self.figure: file_path = tk.filedialog.asksaveasfilename(defaultextension=".png") if file_path: self.figure.savefig(file_path) root = tk.Tk() app = ExcelPlotter(master=root) app.mainloop()帮我增加一个删除当前图像的功能

import akshare as ak import numpy as np import pandas as pd import random import matplotlib.pyplot as plt class StockTradingEnv: def __init__(self): self.df = ak.stock_zh_a_daily(symbol='sh000001', adjust="qfq").iloc[::-1] self.observation_space = self.df.shape[1] self.action_space = 3 self.reset() def reset(self): self.current_step = 0 self.total_profit = 0 self.done = False self.state = self.df.iloc[self.current_step].values return self.state def step(self, action): assert self.action_space.contains(action) if action == 0: # 买入 self.buy_stock() elif action == 1: # 卖出 self.sell_stock() else: # 保持不变 pass self.current_step += 1 if self.current_step >= len(self.df) - 1: self.done = True else: self.state = self.df.iloc[self.current_step].values reward = self.get_reward() self.total_profit += reward return self.state, reward, self.done, {} def buy_stock(self): pass def sell_stock(self): pass def get_reward(self): pass class QLearningAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.epsilon = 1.0 self.epsilon_min = 0.01 self.epsilon_decay = 0.995 self.learning_rate = 0.1 self.discount_factor = 0.99 self.q_table = np.zeros((self.state_size, self.action_size)) def act(self, state): if np.random.rand() <= self.epsilon: return random.randrange(self.action_size) else: return np.argmax(self.q_table[state, :]) def learn(self, state, action, reward, next_state, done): target = reward + self.discount_factor * np.max(self.q_table[next_state, :]) self.q_table[state, action] = (1 - self.learning_rate) * self.q_table[state, action] + self.learning_rate * target if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay env = StockTradingEnv() agent = QLearningAgent(env.observation_space, env.action_space) for episode in range(1000): state = env.reset() done = False while not done: action = agent.act(state) next_state, reward, done, _ = env.step(action) agent.learn(state, action, reward, next_state, done) state = next_state if episode % 10 == 0: print("Episode: %d, Total Profit: %f" % (episode, env.total_profit)) agent.save_model("model-%d.h5" % episode) def plot_profit(env, title): plt.figure(figsize=(12, 6)) plt.plot(env.df.index, env.df.close, label="Price") plt.plot(env.df.index, env.profits, label="Profits") plt.legend() plt.title(title) plt.show() env = StockTradingEnv() agent = QLearningAgent(env.observation_space, env.action_space) agent.load_model("model-100.h5") state = env.reset() done = False while not done: action = agent.act(state) next_state, reward, done, _ = env.step(action) state = next_state plot_profit(env, "QLearning Trading Strategy")优化代码

def draw_stats(self, vals, vals1, vals2, vals3, vals4, vals5, vals6): self.ax1 = plt.subplot(self.gs[0, 0]) self.ax1.plot(vals) self.ax1.set_xlim(self.xlim) locs = self.ax1.get_xticks() locs[0] = self.xlim[0] locs[-1] = self.xlim[1] self.ax1.set_xticks(locs) self.ax1.use_sticky_edges = False self.ax1.set_title(f'Connected Clients Ratio') self.ax2 = plt.subplot(self.gs[1, 0]) self.ax2.plot(vals1) self.ax2.set_xlim(self.xlim) self.ax2.set_xticks(locs) self.ax2.yaxis.set_major_formatter(FuncFormatter(format_bps)) self.ax2.use_sticky_edges = False self.ax2.set_title('Total Bandwidth Usage') self.ax3 = plt.subplot(self.gs[2, 0]) self.ax3.plot(vals2) self.ax3.set_xlim(self.xlim) self.ax3.set_xticks(locs) self.ax3.use_sticky_edges = False self.ax3.set_title('Bandwidth Usage Ratio in Slices (Averaged)') self.ax4 = plt.subplot(self.gs[3, 0]) self.ax4.plot(vals3) self.ax4.set_xlim(self.xlim) self.ax4.set_xticks(locs) self.ax4.use_sticky_edges = False self.ax4.set_title('Client Count Ratio per Slice') self.ax5 = plt.subplot(self.gs[0, 1]) self.ax5.plot(vals4) self.ax5.set_xlim(self.xlim) self.ax5.set_xticks(locs) self.ax5.use_sticky_edges = False self.ax5.set_title('Coverage Ratio') self.ax6 = plt.subplot(self.gs[1, 1]) self.ax6.plot(vals5) self.ax6.set_xlim(self.xlim) self.ax6.set_xticks(locs) self.ax6.yaxis.set_major_formatter(FormatStrFormatter('%.3f')) self.ax6.use_sticky_edges = False self.ax6.set_title('Block ratio') self.ax7 = plt.subplot(self.gs[2, 1]) self.ax7.plot(vals6) self.ax7.set_xlim(self.xlim) self.ax7.set_xticks(locs) self.ax7.yaxis.set_major_formatter(FormatStrFormatter('%.3f')) self.ax7.use_sticky_edges = False self.ax7.set_title('Handover ratio')修改为一张张输出图片

import sys import threading import time from PyQt5.QtWidgets import * from PyQt5 import uic import pandas as pd import random # import pyqtgraph as pg import matplotlib.pyplot as plt from PyQt5.QtWidgets import QGroupBox from PyQt5 import QtWidgets from login_4 import Ui_CK from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas # df = pd.read_excel('shu.xlsx') class MyWindow(QWidget and QMainWindow,Ui_CK): def __init__(self): super().__init__() self.init_ui() groupbox = QGroupBox('Title',self) # self.plot = pg.PlotWidget(enableAutoRange=True) # self.ui.verticalLayout.addWidget(self.plot) # self.curve = self.plot.plot() #self.ui = uic.loadUi("./login_4.ui") def init_ui(self): print('1.1') try: self.ui = uic.loadUi("./login_4.ui") #print(threading.current_thread()) #print(self.ui.__dict__) # print(self.ui.label) # print(self.ui.label.text()) # 查看ui文件中有哪些控件 # 提取要操作的控件 self.user_name_qwidget = self.ui.lineEdit # 单位输入框 self.password_qwidget = self.ui.lineEdit_2 # 二级单位输入框 self.zhicheng_qwidget = self.ui.lineEdit_3 # 职称输入框 self.jiaoyuan_qwidget = self.ui.lineEdit_4 # 教员输入框 self.login_btn = self.ui.pushButton # 登录抽课按钮 self.textBrowser = self.ui.textBrowser # 授课对象显示区域 # 绑定信号与槽函数 self.textBrowser_2 = self.ui.textBrowser_2 # 文本显示区域课程名称 self.textBrowser_3 = self.ui.textBrowser_3 # 文本显示区域课次 self.textBrowser_4 = self.ui.textBrowser_4 # 文本显示区域教研室 self.login_btn.clicked.connect(self.login) self.login_btna = self.ui.pushButton_2 self.login_btna.clicked.connect(lambda: self.plot_q()) except Exception as e: print(e.__class__.__name__, e) def login(self): print('1.2') """登录按钮的槽函数""" #print(self.user_name_qwidget.text()) a = self.user_name_qwidget.text() e = sel 为什么会报错

下面的这段python代码,哪里有错误,修改一下:import numpy as np import matplotlib.pyplot as plt import pandas as pd import torch import torch.nn as nn from torch.autograd import Variable from sklearn.preprocessing import MinMaxScaler training_set = pd.read_csv('CX2-36_1971.csv') training_set = training_set.iloc[:, 1:2].values def sliding_windows(data, seq_length): x = [] y = [] for i in range(len(data) - seq_length): _x = data[i:(i + seq_length)] _y = data[i + seq_length] x.append(_x) y.append(_y) return np.array(x), np.array(y) sc = MinMaxScaler() training_data = sc.fit_transform(training_set) seq_length = 1 x, y = sliding_windows(training_data, seq_length) train_size = int(len(y) * 0.8) test_size = len(y) - train_size dataX = Variable(torch.Tensor(np.array(x))) dataY = Variable(torch.Tensor(np.array(y))) trainX = Variable(torch.Tensor(np.array(x[1:train_size]))) trainY = Variable(torch.Tensor(np.array(y[1:train_size]))) testX = Variable(torch.Tensor(np.array(x[train_size:len(x)]))) testY = Variable(torch.Tensor(np.array(y[train_size:len(y)]))) class LSTM(nn.Module): def __init__(self, num_classes, input_size, hidden_size, num_layers): super(LSTM, self).__init__() self.num_classes = num_classes self.num_layers = num_layers self.input_size = input_size self.hidden_size = hidden_size self.seq_length = seq_length self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True) self.fc = nn.Linear(hidden_size, num_classes) def forward(self, x): h_0 = Variable(torch.zeros( self.num_layers, x.size(0), self.hidden_size)) c_0 = Variable(torch.zeros( self.num_layers, x.size(0), self.hidden_size)) # Propagate input through LSTM ula, (h_out, _) = self.lstm(x, (h_0, c_0)) h_out = h_out.view(-1, self.hidden_size) out = self.fc(h_out) return out num_epochs = 2000 learning_rate = 0.001 input_size = 1 hidden_size = 2 num_layers = 1 num_classes = 1 lstm = LSTM(num_classes, input_size, hidden_size, num_layers) criterion = torch.nn.MSELoss() # mean-squared error for regression optimizer = torch.optim.Adam(lstm.parameters(), lr=learning_rate) # optimizer = torch.optim.SGD(lstm.parameters(), lr=learning_rate) runn = 10 Y_predict = np.zeros((runn, len(dataY))) # Train the model for i in range(runn): print('Run: ' + str(i + 1)) for epoch in range(num_epochs): outputs = lstm(trainX) optimizer.zero_grad() # obtain the loss function loss = criterion(outputs, trainY) loss.backward() optimizer.step() if epoch % 100 == 0: print("Epoch: %d, loss: %1.5f" % (epoch, loss.item())) lstm.eval() train_predict = lstm(dataX) data_predict = train_predict.data.numpy() dataY_plot = dataY.data.numpy() data_predict = sc.inverse_transform(data_predict) dataY_plot = sc.inverse_transform(dataY_plot) Y_predict[i,:] = np.transpose(np.array(data_predict)) Y_Predict = np.mean(np.array(Y_predict)) Y_Predict_T = np.transpose(np.array(Y_Predict))

优化代码 def module_split(self, save_on=True): """ split module data :param save_on: :return: """ for ms in range(self.mod_num): m_sn = self.module_list[ms] module_path = os.path.join(self.result_path_down, m_sn) cols_obj = ChuNengPackMustCols(ms, self.mod_cell_num, self.mod_cell_num) # 传入当前的module序号(如0,1,2,3,4),电芯电压个数,温度NTC个数。 aim_cols = [i for i in cols_obj.total_cols if i in self.df.columns] print(m_sn, aim_cols) self.modules[m_sn] = rename_cols_normal(self.df.loc[:, aim_cols], ms, self.mod_cell_num) print("after change cols name:", ms, m_sn, self.modules[m_sn].columns.tolist()) self.modules[m_sn].dropna(axis=0, how='any', subset=['soc'], inplace=True) volt_col = [f'volt{i}' for i in range(self.mod_cell_num)] temp_col = [f'temp{i}' for i in range(self.mod_cell_num)] self.modules[m_sn].dropna(axis=0, how='any', subset=volt_col, inplace=True) self.modules[m_sn] = stat(self.modules[m_sn], volt_col, temp_col) self.modules[m_sn].reset_index(drop=True, inplace=True) print(self.modules[m_sn]['discharge_ah'].iloc[-1]) self.module_cap[m_sn] = [self.modules[m_sn]['discharge_ah'].iloc[-1], self.modules[m_sn]['charge_ah'].iloc[-1], self.modules[m_sn]['soh'].iloc[-1]] self.module_peaks[m_sn] = list(quick_report(self.modules[m_sn], module_path, f'quick_report_{m_sn[:8]}')) # check soc status mod_soc = self.modules[m_sn]['soc'] self.module_soc_sig[m_sn] = [np.nanmedian(mod_soc), np.max(mod_soc), np.min(mod_soc)] if save_on: single_variables_plot(mod_soc, module_path, f'{m_sn[:8]}_soc_distribution_box.png', 'box', 'SOC') single_variables_plot(mod_soc, module_path, f'{m_sn[:8]}_soc_distribution_violin.png', 'violin', 'SOC')

最新推荐

recommend-type

毕业设计MATLAB_执行一维相同大小矩阵的QR分解.zip

毕业设计matlab
recommend-type

ipython-7.9.0.tar.gz

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

debugpy-1.0.0b3-cp37-cp37m-manylinux2010_x86_64.whl

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

libaacs-devel-0.10.0-1.mga8.i586.rpm

rpm -i xx.rpm 只要报错遇到aacs的可以看看架构是否一致
recommend-type

几个ACM算法pdf.zip

[ACM国际大学生程序设计竞赛题解].pdf ACM模板-清华大学.pdf ACM算法模板(吉林大学).pdf
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

帮我设计一个基于Android平台的便签APP的代码

很抱歉,我是一个语言模型AI,无法提供完整的Android APP代码。但是,我可以给您一些设计便签APP的建议和思路。 1. 界面设计 首先考虑APP的界面设计,便签APP通常需要一个主界面用于显示所有的便签,以及一个编辑界面用于编辑单个便签。主界面可以采用列表的形式,列出所有的便签,每个便签可以显示标题和摘要内容。在编辑界面中,用户可以输入标题和正文内容,并且可以设置提醒时间、标签、优先级等。 2. 数据存储 便签APP需要一个数据存储的方案,可以考虑使用SQLite数据库来存储便签数据。每个便签可以存储标题、正文内容、提醒时间、标签、优先级等信息。 3. 便签操作 便签APP
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。