0

我正在通过 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 子进程的任何想法?

4

1 回答 1

0

这是实现您的目标的解决方案。虽然这不一定轮询 MSC Nastran,但此解决方案确实允许您在 MSC Nastran 运行时检查输出文件。

该解决方案涉及使用看门狗库。我在 MSC Nastran 运行期间使用看门狗库来读取日志文件。

下面是一个功能示例。

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 script
于 2020-03-04T05:08:45.780 回答