Python:打开函数无法打开带有追加的新文件

标签 python ansible

我正在编写自定义 ansible 模块。

调用方法如下:

  - name: mymodule.yml -> Run mymodule
    mymodule:
      test_file: "{{ item }}"
      env_file: "{{ environment_file.stdout }}"
      out_dir: "{{ nginx_folder }}/{{ rv_dir_name.stdout }}"
      base_url: "{{ results_base_url }}"
    become: yes

在某个时间点,在模块内,调用了以下 python 命令:

# use file for the stderr descriptor of the subprocess.call
try:
    # os.mkdir(_out_dir, 0755 )
    ferr = open('std_err.log', 'w')
    # fout = open('std_out.log', 'w')   
    fout = open(_out_dir + "/" + 'std_out.log', 'a')
except Exception as exc:
    module.fail_json(msg="Hello: " + str(exc))
# fout = open('std_out.log', 'a')

当我执行模块时,以下行给出了这个错误:

"msg": [Errno 2] No such file or directory: '/var/www/html/newman-tests/2019-03-25_09:34:04/std_out.log'",

为什么创建/打开文件失败,尽管事实是:

a) 模块被调用 become: yes

b) open 是用 a 调用的,如果文件不存在,它应该创建文件吗?

编辑:文件夹确实存在,因为提前调用了

os.mkdir(_out_dir, 0755 )

失败,目录存在

此外,在我的模块下面的几行中,我称之为:

rc = call(["newman", "run", _test_file, "-k", "-e", _env_file, "-r", "htmlextra,cli", "--reporter-html-report", "--reporter-htmlextra-export", _output], stderr=ferr)

在哪里

_output = _out_dir + "/" + _report_fname

_out_dir 与上述 open 失败的目录相同

(这工作正常)

最佳答案

a+ 文件不存在时创建。读取的初始文件位置在文件的开头,但输出附加到文件的末尾。

关于Python:打开函数无法打开带有追加的新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55333161/

相关文章:

ssh - Ansible:在动态 ec2 上设置用户

linux - ansible extra vars 散列过滤器

linux - 是否有一些相当于 "failed_when"的 Ansible 成功

cron - Ansible:在一台主机上设置一个 cron 作业

python - 接受扩展参数和元组的函数

python - cProfile 未运行

Python3 无法将字符串转换为 dict 或 json

python - 解密 fernet token 时修复无效签名

python - Pandas - 检查列标签是否存在于另一列的值中并更新该列

linux - 无法通过 Ansible ping 我的远程计算机