【问题标题】:python on linux can't find file inside functionlinux上的python在函数内找不到文件
【发布时间】: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


    【解决方案1】:

    这可能是一种竞争条件:当您的代码想要从文件中读取输出时,程序尚未完成且输出文件尚不存在。尝试使用“睡眠”循环等待要读取的文件可用。另一种可能是文件权限不匹配。

    【讨论】:

    • 谢谢! Sleep 确实消除了错误,不幸的是,这个函数是在循环中调用的......然后我会做一些 try 语句。
    • 只是把它留在这里以备将来使用。我最终使用了 subprocess 模块而不是 os.system 。将 cmd 格式化为列表,然后按照 [docs.python.org/2/library/subprocess.html] 和 [stackoverflow.com/questions/11269575/… 中的建议使用 subprocess.check_call(cmd, stdout=DEVNULL, stderr=subprocess.STDOUT, close_fds=True)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2015-08-03
    • 2018-12-12
    • 2013-03-19
    • 2013-07-17
    相关资源
    最近更新 更多