我正在通过Python运行Nastran模拟。
nastran=subprocess.run([nastrandir,fn,"parallel = 4","old=no",outputarg])这些模拟往往会在没有反馈的情况下运行相当长的一段时间,所以我正在尝试自动读取输出文件中的相关数据并打印出来。
为此,我需要在子流程运行时运行一些代码。然而,这似乎不起作用。作为一个简单的测试,我在subprocess命令下编写了以下代码:
while nastran.poll() is None:
print("Still working \r")
time.sleep(delay)
print("Still working. \r")
time.sleep(delay)
print("Still working.. \r")
time.sleep(delay)
print("Still working...\r")
time.sleep(delay)不幸的是,代码似乎被subprocess命令卡住了,等待它完成,此时nastran变成了一个CompletedProcess类,不能再被轮询,这是我收到的错误。
你知道如何让Python正确地轮询我的Nastran子进程吗?
发布于 2020-03-04 13:08:46
这里有一个解决方案来实现你的目标。虽然这不一定轮询MSC Nastran,但此解决方案允许您在MSC Nastran运行时检查输出文件。
该解决方案涉及到使用watchdog库。在MSC Nastran运行期间,我使用watchdog库来读取日志文件。
下面是一个功能示例。
import watchdog.events
from watchdog.observers import Observer
import subprocess
# Class defining a scan folder
class ScanFolder:
def __init__(self, path):
self.path = path
self.event_handler = watchdog.events.PatternMatchingEventHandler(patterns=["*.log"],
ignore_patterns=[],
ignore_directories=True)
self.event_handler.on_any_event = self.parse_log
self.observer = Observer()
self.observer.schedule(self.event_handler, self.path, recursive=False)
self.observer.start()
def parse_log(self, event):
if event.event_type is not 'deleted':
name_of_file = event.src_path.replace('.\\', '').replace('./', '')
# The code that reads the LOG file goes here
print('Change detected in the following file')
print(name_of_file)
def stop_actions(self):
self.observer.stop()
# Start monitoring
path_to_monitor = '.'
scan_folder = ScanFolder(path_to_monitor)
# Run MSC Nastran
nastran_command = '/msc/MSC_Nastran/20181/bin/msc20181'
subprocess.call([nastran_command, 'nastran', 'dsoug1.dat', 'batch=NO'])
print('End of script')
# output
# MSC Nastran V2018.1 (Intel Linux 4.15.0-88-generic) Tue Mar 3 21:01:43 2020
#
# *** SYSTEM INFORMATION MESSAGE (pgm: nastran, fn: estimate_job_requirements)
# Starting ESTIMATE, please wait...
#
# *** USER INFORMATION MESSAGE (pgm: nastran, fn: estimate_job_requirements)
# Estimated bpool=7664.4MB
# Estimated DOF=2
# Estimated memory=7959.5MB
# Estimated disk=1.2MB
# MSC Nastran beginning job dsoug1.
# Change detected in the following file
# dsoug1.log
# Change detected in the following file
# dsoug1.log
# Change detected in the following file
# dsoug1.log
# Change detected in the following file
# dsoug1.log
# ...
# Change detected in the following file
# dsoug1.log
# Change detected in the following file
# dsoug1.log
# MSC Nastran job dsoug1 completed.
# End of scripthttps://stackoverflow.com/questions/55244432
复制相似问题