小编Mac*_*eek的帖子

检查fstream是文件还是目录

我正在使用C++ fstream来读取配置文件.

#include <fstream>
std::ifstream my_file(my_filename);
Run Code Online (Sandbox Code Playgroud)

现在,如果我传递一个目录的路径,它会默默地忽略它.my_file.good()即使my_filename是目录,Eg 也会返回true .由于这是我的程序的意外输入,我喜欢检查它,并抛出异常.

如何检查刚打开的fstream是否是常规文件,目录或流?

我似乎无法找到一种方法:

  • 从给定的ifstream获取文件描述符.
  • 使用其他一些机制在ifstream中查找此信息.

一些论坛讨论中,有人认为这两者都不可能,因为这是依赖于操作系统的,因此永远不会成为fstream C++标准的一部分.

我能想到的唯一选择是重写我的代码以完全摆脱ifstream并使用文件描述符(*fp)的C方法,以及fstat():

#include <stdio.h>
#include <sys/stat.h>
FILE *fp = fopen(my_filename.c_str(), "r");
// skip code to check if fp is not NULL, and if fstat() returns != -1
struct stat fileInfo;
fstat(fileno(fp), &fileInfo);
if (!S_ISREG(fileInfo.st_mode)) {
    fclose(fp);
    throw std::invalid_argument(std::string("Not a regular file ") + my_filename);
}
Run Code Online (Sandbox Code Playgroud)

我更喜欢fstream.因此,我的问题.

c++ fstream ifstream c++11 fstat

9
推荐指数
1
解决办法
6091
查看次数

Ansible local_action 在没有本地 ssh 守护进程的主机上

如果该控制服务器没有运行 SSH 守护程序,我如何在 Ansible 控制服务器上运行本地命令?

如果我运行以下剧本:

- name: Test commands
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Test local action
      local_action: command echo "hello world"
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

fatal: [localhost]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host localhost port 22: Connection refused", "unreachable": true}

似乎local_action与 相同delegate_to: 127.0.0.1,因此 Ansible 尝试通过 ssh 连接到本地主机。但是,本地控制器主机上没有运行 SSH 守护程序(仅在远程机器上)。

所以我的直接问题是如何从 Ansible 运行特定命令,而无需 Ansible 首先尝试通过 SSH 连接到 localhost。


关键的补充,不在原来的问题中:

我的 host_vars 包含以下行:

ansible_connection: …
Run Code Online (Sandbox Code Playgroud)

ansible

8
推荐指数
2
解决办法
5429
查看次数

如何在 Python 中对协变可变集合类使用类型提示?

我正在尝试在 Python 中创建一个类似协变集合的类,如下所示:

from typing import Generic, TypeVar, List, cast

class Animal():
    pass

class Dog(Animal):
    pass

class Cat(Animal):
    pass

class Zoo():
    def __init__(self, items: List[Animal]):
        self._items = items.copy()  # type: List[Animal]

    def add(self, animal: Animal) -> None:
        self._items.append(animal)

    def animal_count(self) -> int:
        return len(self._items)

    def get_animals(self) -> List[Animal]:
        return self._items.copy()

class DogHouse(Zoo):
    def __init__(self, items: List[Dog]):
        self._items = items.copy()  # type: List[Dog]

    def add(self, dog: Dog) -> None:
        assert isinstance(dog, Dog)
        self._items.append(dog)
Run Code Online (Sandbox Code Playgroud)

简而言之,我喜欢子类化Zoo,这样它只需要特定类型的 Animal 。在本例中,aDogHouse仅包含Dog …

python covariance type-hinting

5
推荐指数
1
解决办法
1738
查看次数

Python argparse:列出用法中的各个选项

我有一个需要多个参数的程序,例如

breakfast.py --customer=vikings eggs sausage bacon
Run Code Online (Sandbox Code Playgroud)

其中“鸡蛋”、“香肠”和“培根”可以从特定选项列表中指定。

现在我喜欢这样的输出breakfast.py --help

usage: breakfast.py [-h] [--customer CUSTOMER] INGREDIENT [INGREDIENT ...]

positional arguments:
  your choice of ingredients:
    bacon              Lovely bacon
    egg                The runny kind
    sausage            Just a roll
    spam               Glorious SPAM
    tomato             Sliced and diced

optional arguments:
  -h, --help           show this help message and exit
  --customer CUSTOMER  salutation for addressing the customer
Run Code Online (Sandbox Code Playgroud)

我尝试了两种方法,但到目前为止都失败了。

使用参数选择:

import argparse

parser = argparse.ArgumentParser()

toppings = {
    'bacon': "Lovely bacon",
    'egg': 'The runny kind',
    'sausage': 'Just a …
Run Code Online (Sandbox Code Playgroud)

python argparse

0
推荐指数
2
解决办法
4242
查看次数

标签 统计

python ×2

ansible ×1

argparse ×1

c++ ×1

c++11 ×1

covariance ×1

fstat ×1

fstream ×1

ifstream ×1

type-hinting ×1