問題描述
Python 和 if 語句 (Python and if statement)
I'm running a script to feed an exe file a statement like below:
for j in ('90.','52.62263.','26.5651.','10.8123.'):
if j == '90.':
z = ('0.')
elif j == '52.62263.':
z = ('0.', '72.', '144.', '216.', '288.')
elif j == '26.5651':
z = ('324.', '36.', '108.', '180.', '252.')
else:
z = ('288.', '0.', '72.', '144.', '216.')
for k in z:
exepath = os.path.join('\Program Files' , 'BRL‑CAD' , 'bin' , 'rtarea.exe')
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = exepath + '‑j' + str(el) + '‑k' + str(z)
process=Popen('echo ' + cmd, shell=True, stderr=STDOUT )
print process
I'm using the command prompt and when I run the exe with these numbers there are times when It doesn't seem to be in order. Like sometimes it will print out 3 statements of the 52.62263 but then before they all are printed it will print out a single 26.5651 and then go back to 52.62263. It's not just those numbers that act like this. Different runs it may be different numbers (A 52.62263 between "two" 90 statements) . All in all, I want it to print it in order top to bottom. Any suggestions and using my code any helpful solutions? thanks!
‑‑‑‑‑
參考解法
方法 1:
z = ('0.')
is not a tuple, therefore your for k in z
loop will iterate over the characters "0" and ".". Add a comma to tell python you want it to be a tuple:
z = ('0.',)
方法 2:
I think what's happening right now is that you are not waiting for those processes to finish before they're printed. Try something like this in your last 2 lines:
from subprocess import Popen, STDOUT
stdout, stderr = Popen('echo ' + cmd, shell=True, stderr=STDOUT).communicate()
print stdout
方法 3:
What eduffy said. And this is a little cleaner; just prints, but you get the idea:
import os
data = {
'90.': ('0.',),
'52.62263.': ('0.', '72.', '144.', '216.', '288.'),
'26.5651.': ('324.', '36.', '108.', '180.', '252.'),
'10.8123.': ('288.', '0.', '72.', '144.', '216.'),
}
for tag in data:
for k in data[tag]:
exepath = os.path.join('\Program Files', 'BRL‑CAD', 'bin', 'rtarea.exe')
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = exepath + ' ‑el ' + str(tag) + ' ‑az ' + str(data[tag])
process = 'echo ' + cmd
print process
方法 4:
Since you've made a few posts about this bit of code, allow me to just correct/pythonify/beautify the whole thing:
for j,z in {
'90.' : ('0.',) ,
'52.62263.' : ('0.', '72.', '144.', '216.', '288.') ,
'26.5651.' : ('324.', '36.', '108.', '180.', '252.') ,
'10.8123.' : ('288.', '0.', '72.', '144.', '216.')
}.iteritems():
for k in z:
exepath = os.path.join('\Program Files' , 'BRL‑CAD', 'bin' , 'rtarea.exe')
exepath = '"%s"' % os.path.normpath(exepath)
cmd = exepath + '‑j' + str(el) + '‑k' + z
process = Popen('echo ' + cmd, shell=True, stderr=STDOUT )
print process
(by Tyler、eduffy、John G、user447688、Kenan Banks)