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)) 怎么检测该段程序是否运行完毕

时间: 2024-02-13 21:03:29 浏览: 25
可以在程序运行完毕后,使用一个标志变量来表示程序已经运行完毕,例如在该段程序中,可以在最后添加一行代码 `self.is_finished = True` 来表示程序已经运行完毕。然后在调用该程序的地方,可以使用一个循环来不断检测该标志变量是否为True,直到程序运行完毕才继续执行后面的代码。例如: ``` chitgpt.plot() # 调用程序 # 检测程序是否运行完毕 while not chitgpt.is_finished: time.sleep(1) # 等待1秒钟 continue # 程序已经运行完毕,继续执行后面的代码 print("程序已经运行完毕!") ``` 这样就可以检测该段程序是否运行完毕了。需要注意的是,在使用循环等待程序运行完毕时,需要添加一些等待时间,否则可能会出现死循环的情况。
相关问题

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是否运行完毕

要检测该段程序中 `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,则表示程序执行成功,否则表示程序执行失败。

def plot(self): self.is_running = False pwd_path = os.getcwd() script_path = os.path.join(pwd_path, 'algo_galileo_2e235eb933c9_deg90\\An_test') folder_path = os.path.join(pwd_path, 'source\\Test_Source_Data') os.chdir(script_path) os.system('powershell -Command "./csv_output.sh {0}"'.format(folder_path)) time.sleep(30) 这段代码中,怎么把路径pwd_path改为os.getcwd()的上级目录

可以使用os.path.abspath(os.path.join(os.getcwd(), ".."))来获取当前工作目录的上级目录,然后将其赋值给pwd_path。所以,可以将第三行代码改为: ``` pwd_path = os.path.abspath(os.path.join(os.getcwd(), "..")) ``` 这样就能获取到当前工作目录的上级目录了。

相关推荐

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

matplotlib 曲线图 和 折线图 plt.plot()实例

在Python的可视化库matplotlib中,`plt.plot()`函数是用于绘制曲线图和折线图的主要工具。本实例展示了如何利用这个函数创建具有不同特性的图形。以下是对matplotlib中曲线图和折线图的理解以及`plt.plot()`的具体...
recommend-type

服务器虚拟化部署方案.doc

服务器、电脑、
recommend-type

北京市东城区人民法院服务器项目.doc

服务器、电脑、
recommend-type

求集合数据的均方差iction-mast开发笔记

求集合数据的均方差
recommend-type

Wom6.3Wom6.3Wom6.3

Wom6.3Wom6.3Wom6.3
recommend-type

VMP技术解析:Handle块优化与壳模板初始化

"这篇学习笔记主要探讨了VMP(Virtual Machine Protect,虚拟机保护)技术在Handle块优化和壳模板初始化方面的应用。作者参考了看雪论坛上的多个资源,包括关于VMP还原、汇编指令的OpCode快速入门以及X86指令编码内幕的相关文章,深入理解VMP的工作原理和技巧。" 在VMP技术中,Handle块是虚拟机执行的关键部分,它包含了用于执行被保护程序的指令序列。在本篇笔记中,作者详细介绍了Handle块的优化过程,包括如何删除不使用的代码段以及如何通过指令变形和等价替换来提高壳模板的安全性。例如,常见的指令优化可能将`jmp`指令替换为`push+retn`或者`lea+jmp`,或者将`lodsbyteptrds:[esi]`优化为`moval,[esi]+addesi,1`等,这些变换旨在混淆原始代码,增加反逆向工程的难度。 在壳模板初始化阶段,作者提到了1.10和1.21两个版本的区别,其中1.21版本增加了`Encodingofap-code`保护,增强了加密效果。在未加密时,代码可能呈现出特定的模式,而加密后,这些模式会被混淆,使分析更加困难。 笔记中还提到,VMP会使用一个名为`ESIResults`的数组来标记Handle块中的指令是否被使用,值为0表示未使用,1表示使用。这为删除不必要的代码提供了依据。此外,通过循环遍历特定的Handle块,并依据某种规律(如`v227&0xFFFFFF00==0xFACE0000`)进行匹配,可以找到需要处理的指令,如`push0xFACE0002`和`movedi,0xFACE0003`,然后将其替换为安全的重定位值或虚拟机上下文。 在结构体使用方面,笔记指出壳模板和用户代码都会通过`Vmp_AllDisassembly`函数进行解析,而且0x8和0x10字段通常都指向相同的结构体。作者还提到了根据`pNtHeader_OptionalHeader.Magic`筛选`ESI_Matching_Array`数组的步骤,这可能是为了进一步确定虚拟机上下文的设置。 这篇笔记深入解析了VMP技术在代码保护中的应用,涉及汇编指令的优化、Handle块的处理以及壳模板的初始化,对于理解反逆向工程技术以及软件保护策略有着重要的参考价值。
recommend-type

管理建模和仿真的文件

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

【进阶】音频处理基础:使用Librosa

![【进阶】音频处理基础:使用Librosa](https://picx.zhimg.com/80/v2-a39e5c9bff1d920097341591ca8a2dfe_1440w.webp?source=1def8aca) # 2.1 Librosa库的安装和导入 Librosa库是一个用于音频处理的Python库。要安装Librosa库,请在命令行中输入以下命令: ``` pip install librosa ``` 安装完成后,可以通过以下方式导入Librosa库: ```python import librosa ``` 导入Librosa库后,就可以使用其提供的各种函数
recommend-type

python中字典转换成json

在Python中,你可以使用`json`模块将字典转换为JSON格式的字符串。下面是一个简单的示例: ```python import json # 假设我们有一个字典 dict_data = { "name": "John", "age": 30, "city": "New York" } # 使用json.dumps()函数将字典转换为JSON json_string = json.dumps(dict_data) print(json_string) # 输出:{"name": "John", "age": 30, "city": "New York"}
recommend-type

C++ Primer 第四版更新:现代编程风格与标准库

"Cpp Primer第四版中文版(电子版)1" 本书《Cpp Primer》第四版是一本深入浅出介绍C++编程语言的教程,旨在帮助初学者和有经验的程序员掌握现代C++编程技巧。作者在这一版中进行了重大更新,以适应C++语言的发展趋势,特别是强调使用标准库来提高编程效率。书中不再过于关注底层编程技术,而是将重点放在了标准库的运用上。 第四版的主要改动包括: 1. 内容重组:为了反映现代C++编程的最佳实践,书中对语言主题的顺序进行了调整,使得学习路径更加顺畅。 2. 添加辅助学习工具:每章增设了“小结”和“术语”部分,帮助读者回顾和巩固关键概念。此外,重要术语以黑体突出,已熟悉的术语以楷体呈现,以便读者识别。 3. 特殊标注:用特定版式标注关键信息,提醒读者注意语言特性,避免常见错误,强调良好编程习惯,同时提供通用的使用技巧。 4. 前后交叉引用:增加引用以帮助读者理解概念之间的联系。 5. 额外讨论和解释:针对复杂概念和初学者常遇到的问题,进行深入解析。 6. 大量示例:提供丰富的代码示例,所有源代码都可以在线获取,便于读者实践和学习。 本书保留了前几版的核心特色,即以实例教学,通过解释和展示语言特性来帮助读者掌握C++。作者的目标是创作一本清晰、全面、准确的教程,让读者在编写程序的过程中学习C++,同时也展示了如何有效地利用这门语言。 《Cpp Primer》第四版不仅适合C++初学者,也适合想要更新C++知识的老手,它全面覆盖了C++语言的各个方面,包括基础语法、类、模板、STL(Standard Template Library)等,同时引入了现代C++的特性,如智能指针、RAII(Resource Acquisition Is Initialization)、lambda表达式等,使读者能够跟上C++语言的发展步伐,提升编程技能。