【发布时间】:2018-08-21 14:58:00
【问题描述】:
我正在 linux 上的 python 2.7.12 上编写一个脚本,其中包含一堆运行外部程序的函数...
在某些时候,我有一个运行程序的函数,该程序生成一个外部文件。该函数的下一步是读取外部文件并进行一些处理。
功能是
def RunProgram(input, options)
input_file=str(input)
options=str(options)
cmd=str('program + ' input_file + '--flag ' + options + ' --out temp.log &> /dev/null')
#print(cmd)
#print(cmd)
os.system(cmd)
with open('path_to_file/temp.log') as fp:
for i, line in enumerate(fp):
if i == 2:
#print(line)
solution=str(line) #stores 3rd line of log file
elif i > 2:
break
return solution
不知何故,虽然外部程序运行并且我看到从 bash shell 创建的 temp.log,但函数退出并出现错误
IOError: [Errno 2] No such file or directory: 'path_to_file/temp.log'
如果在 os.system(cmd) 之后的函数中我放置
print(os.path.exists('path_to_file/temp.log'))
print(os.path.isfile('path_to_file/temp.log'))
我得到 2 个错误,但如果我在运行函数并得到错误后运行这些命令,我得到两个都为真,并且我使用 ls 看到目录中的文件。
一旦我在 temp.log 已经存在的情况下再次运行该函数,该函数就可以工作了。
我检查了 os.getcwd() 并且会话在正确的目录中运行。我还检查了我对 temp.log 的读取权限
..有什么想法吗?
【问题讨论】:
标签: python python-2.7 io