-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathTestRunFoamApplication.py
191 lines (164 loc) · 9 KB
/
TestRunFoamApplication.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#***************************************************************************
#* *
#* Copyright (c) 2016 - Qingfeng Xia <qingfeng.xia()eng.ox.ac.uk> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#***************************************************************************
from __future__ import print_function
import platform
import subprocess
import os
import sys
import os.path
PACKAGE_PARENT = '../..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
import FoamCaseBuilder
from FoamCaseBuilder.utility import *
from FoamCaseBuilder.utility import _fromWindowsPath, _toWindowsPath
from FoamCaseBuilder.config import _detectFoamDir, _detectFoamVersion
#
cmd = """ bash -c 'source "/opt/openfoam4/etc/bashrc" && cd "/tmp/TestCase" && ideasUnvToFoam "/tmp/TestCase/TestCase.unv"' """
#cmd = 'source /opt/openfoam4/etc/bashrc'
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell = True) # must be run in shell mode to use source
(output, error) = proc.communicate()
if error: print(error)
print(output)
def test_bash_QProcess():
from PyQt4 import QtCore
process = QtCore.QProcess()
process.setProcessChannelMode(QtCore.QProcess.MergedChannels)
#process.finished.connect()
#QProcess works wtih `bash -l -c` but not `bash -i -c`
#process.start('bash', ['-l', '-c', 'echo $WM_PROJECT_DIR']) # work if start in gnome-terminal
#~/.bashrc is not recognized, need a full path to the etc file
#process.start('bash', ['-c', '"source ~/.bashrc && echo $WM_PROJECT_DIR"']) #
process.start('bash', ['-c', '"source ~/.bashrc && echo $WM_PROJECT_DIR"'])
print('Test in QProcess')
if process.waitForFinished():
print(process.readAll())
print('End of Test in QProcess')
def runFoamCommand(cmd):
""" run OpenFOAM command via bash with OpenFOAM setup sourced into ~/.bashrc
wait until finish, caller is not interested on output but whether succeeded
source foam_dir/etc/bashrc before run foam related program
`shell=True` does not work if freeCAD is not started in shell terminal
Bash on Ubuntu on Windows, may need case path translation done in Builder
"""
if isinstance(cmd, list):
_cmd = _translateFoamCasePath(cmd) # do not modify input parameter, it may be used outside somewhere
#cmd = ' '.join(cmd)
else:
print("Warning: runFoamCommand() command and options must be specified in a list")
cmdline = ' '.join(_cmd)
print("Run command: ", cmdline)
# this is the method works for both started in terminal and GUI launcher
env_setup_script = "source {}/etc/bashrc".format(getFoamDir())
#env_setup_script = "source ~/.bashrc"
cmdline_1 = ['bash', '-c', ' '.join([env_setup_script, '&&'] + _cmd)]
#cmdline = """bash -i -c '{} && {}' """.format(env_setup_script, ' '.join(_cmd))
#cmdline_1 = """bash -c ' {} && {}'""".format(env_setup_script, cmdline)
print("Run command_1: ", cmdline_1) # get correct command line, correct in terminal, but error in python
out = subprocess.check_output(cmdline_1, stderr=subprocess.PIPE)
# bug: FreeCAD exit due to runFoamCommand() is called immediately after another runFoamCommand() using `bash -i`
# '-l' means '--login' works in terminal, while '-i' means '--interactive' works from unity GUI launcher
#out = subprocess.check_output(['bash', '-l', '-c', cmdline], stderr=subprocess.PIPE)
if _debug: print(out)
"""
# method3: error even at the first runFoamCommand(), running from terminal
process = subprocess.Popen(['bash', '-i', '-c', cmdline], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout, stderr = process.communicate()
exitCode = process.returncode
if _debug:
print(stdout)
if (exitCode != 0):
if _debug:
print(stderr)
#else: # should allow runFoamCommand to fail
#raise SystemError("Error in foamRunCommand:".format(cmdline), exitCode)
return exitCode
"""
'''
source foam_dir/etc/bashrc before run foam related program
`shell=True` does not work if freeCAD is not started in shell terminal
>python3 subprocess.check_output"
b'/opt/openfoam4\n'
>Exit code: 1
>python2 subprocess.check_output"
/opt/openfoam4
'''
def test_runBashCommand(cmd):
#leading and trailing space in case path quote " path " will cause error
#cmd = ["icoFoam", '-help']
#cmdline = """bash -i -c '{}' """.format(' '.join(cmd))
cmdline = ' '.join(cmd)
print(cmdline)
out = subprocess.check_output(['bash', '-i', '-c', cmdline], stderr=subprocess.PIPE)
print(out)
#test_runCommand1() #fine in freecad without in console
#foam_dir = subprocess.check_output(['bash', '--rcfile', '~/.bashrc' '-c', ' echo $WM_PROJECT_DIR'], stderr=subprocess.PIPE)
print("test on platform", platform.system())
print("Foam dir and version detectoin")
if platform.system() == 'Windows': # ubuntu on windows 10
#cmdline = ['bash', '-i', '-c', 'source ~/.bashrc && echo $WM_PROJECT_DIR']
#print(cmdline)
#foam_dir = subprocess.check_output('bash -c "source ~/.bashrc && echo test $WM_PROJECT_DIR"', stderr=subprocess.PIPE) # error
case = 'D:\\'
output_file = case + os.path.sep + "output.txt"
output_file_wsl = _fromWindowsPath(output_file)
print("test of path translation")
print("original win path:", output_file)
print("to WSL path:", _fromWindowsPath(output_file))
print("translated back to win path:", _toWindowsPath(output_file_wsl))
cmdline = 'transformPoints -case "D:\TestCase" -scale "(1 1 1)"'
print("translation of cmdline:", cmdline)
if True:
#cmd = 'echo $HOME' # working, but user export var is not working like WM_PROJECT_DIR
cmd = 'export WM_PROJECT_DIR=/opt/openfoam4 && echo $WM_PROJECT_DIR' # not working
#ret = subprocess.call('bash -c "source ~/.bashrc && {} > {}"'.format(cmd, output_file_wsl)) # no error, no output
# by `bash script.sh`, export is supported, but "source bashrc is still not working"
cmd = 'source "$HOME/.bashrc" && echo $WM_PROJECT_DIR' # not working
foam_script_file = case + os.path.sep + "temp_foam_script.sh"
with open(foam_script_file, 'w') as wf: # existent file will be erased
wf.write('{} > "{}"'.format(cmd, output_file_wsl)) # single line to avoid end of line error
ret = subprocess.call('bash "{}"'.format(_fromWindowsPath(foam_script_file))) # no error, no output
#bash --init-file ~/.bashrc -c declare -x WM_PROJECT_DIR=/opt/openfoam4 && echo $WM_PROJECT_DIR
#cmd: bash -i -c "source /home/qingfeng/.bashrc && echo test$WM_PROJECT_DIR"
#print("type of return value", type(ret))
with open(output_file) as f:
result = f.read().strip()
#assert 'test' == result
print("`{}` exit with code: {}, and result is `{}`".format(cmd, ret, result))
else:
cmd = ['echo', "$HOME"] # $WM_PROJECT_DIR
print('runFoamCommandOnWSL()')
foam_dir = runFoamCommandOnWSL(None, cmd, output_file)
print(foam_dir)
else:
test_bash_QProcess()
#`bash -l -c` will not work with python subprocess.check_output
foam_dir = subprocess.check_output(['bash', '-i', '-c', 'echo $WM_PROJECT_DIR'], stderr=subprocess.PIPE)
print(foam_dir)
#print(stderr)
case_path = '/home/qingfeng/Documents/TestCase'
if os.path.exists(case_path):
cmd = ['transformPoints','-case', '"' + case_path + '"', '-scale', '"(1 1 1)"']
#test_runBashCommand(cmd) # error
cmd1 = ['transformPoints', '-scale', '"(1 1 1)"']
runFoamApplication(case_path, cmd1)
runFoamApplication(None, 'simpleFoam -help')