所以我正在尝试使用“较新的”子进程在 bash shell 中执行一个 fortran 程序...不确定我做错了什么,但如果我这样做了
result = os.system('./get_cpus -inp ./output_00076 -xc {:.4e} -yc {:.4e} -zc {:.4e} -rad {:.4e}'.format(loc[0],loc[1],loc[2],rad) )
我在结果中得到了 Fortran 程序的输出(来自 get_cpus)。想法似乎工作正常......但如果我这样做:
result = subprocess.check_output(['./get_cpus',
'-inp ./output_00076',
'-xc {:.4e}'.format(loc[0]),
'-yc {:.4e}'.format(loc[1]),
'-zc {:.4e}'.format(loc[2]),
'-rad {:.4e}'.format(rad)])
我得到一个错误:
./get_cpus -inp ./output_00076 -xc 3.1670e-01 -yc 9.6000e-02 -zc 2.4170e-01 -rad 2.0360e-03
forrtl: severe (59): list-directed I/O syntax error, unit -5, file Internal List-Directed Read
Image PC Routine Line Source
get_cpus 0000000000409CD8 Unknown Unknown Unknown
get_cpus 000000000042AF2D Unknown Unknown Unknown
get_cpus 0000000000429696 Unknown Unknown Unknown
get_cpus 00000000004065E7 get_cpus_IP_read_ 280 get_cpus.f90
get_cpus 00000000004029B1 MAIN__ 46 get_cpus.f90
get_cpus 000000000040297E Unknown Unknown Unknown
libc-2.22.so 00007FFFECE456D5 __libc_start_main Unknown Unknown
get_cpus 00000000004028A9 Unknown Unknown Unknown
Traceback (most recent call last):
File "findCPUs.py", line 45, in <module>
'-rad {:.4e}'.format(rad)])
File "/nasa/pkgsrc/2014Q4/lib/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['./get_cpus', '-inp ./output_00076', '-xc 3.1670e-01', '-yc 9.6000e-02', '-zc 2.4170e-01', '-rad 2.0360e-03']' returned non-zero exit status 59
“CalledProcessError: Command”在我看来没问题......
我已经尝试使用“shell=True”进行此操作,然后让程序运行,但输入都丢失了,因为 fortran 代码返回了“usage”语句(说明我需要输入参数)。 ???例如-
result = subprocess.check_output(['./get_cpus',
'-inp ./output_00076',
'-xc {:.4e}'.format(loc[0]),
'-yc {:.4e}'.format(loc[1]),
'-zc {:.4e}'.format(loc[2]),
'-rad {:.4e}'.format(rad)],
shell=True, stdin=subprocess.PIPE)
我做错了什么??
请您参考如下方法:
使用 os.system,您可以自己编写参数字符串。它有效,但它很丑陋,容易代码注入(inject),并且如果您忘记引用它们,则对某些带空格的参数不稳健。所以 subprocess 是正确的选择。
现在,需要使用带有参数列表的subprocess。
这里你的论点 split 是错误的。例如,您将 2 个参数作为一个参数(空格分隔)包括在内:
'-xc {:.4e}'.format(loc[0]),
这个“论据”发给系统就像
"-xc .4555"
(是的,带引号),这会混淆参数解析。
修复:正确分隔参数:
result = subprocess.check_output(['./get_cpus',
'-inp','./output_00076',
'-xc','{:.4e}'.format(loc[0]),
'-yc','{:.4e}'.format(loc[1]),
'-zc','{:.4e}'.format(loc[2]),
'-rad','{:.4e}'.format(rad)],
stdin = subprocess.PIPE)
你也不需要shell=True。除了快速破解外,它几乎从不有用。通常不能解决任何问题,并且是一种安全责任(代码注入(inject))
