相关疑难解决方法(0)

什么是python"with"语句专为什么设计的?

with今天第一次遇到了Python 语句.我已经使用Python几个月了,甚至不知道它的存在!鉴于其地位有点模糊,我认为值得问:

  1. 什么是with设计用于的Python 语句?
  2. 你用它来做什么?
  3. 是否有任何我需要注意的问题,或与其使用相关的常见反模式?任何try..finally比它更好用的情况with
  4. 为什么它的使用范围更广?
  5. 哪些标准库类与它兼容?

python language-features with-statement

396
推荐指数
7
解决办法
9万
查看次数

如何在python中编写和保存html文件?

这就是我所知道的如何编写和保存它

Html_file= open"(filename","w")
Html_file.write()
Html_file.close
Run Code Online (Sandbox Code Playgroud)

但是,如果我想写一个非常长的代码,我如何保存到文件:

   1   <table border=1>
   2     <tr>
   3       <th>Number</th>
   4       <th>Square</th>
   5     </tr>
   6     <indent>
   7     <% for i in range(10): %>
   8       <tr>
   9       <td><%= i %></td>
   10      <td><%= i**2 %></td>
   11      </tr>
   12    </indent>
   13  </table>
Run Code Online (Sandbox Code Playgroud)

python

27
推荐指数
2
解决办法
11万
查看次数

理解Python'with'语句

我试图了解这些之间是否存在差异,以及这种差异可能是什么.

方案一:

file_obj = open('test.txt', 'r')

with file_obj as in_file:
    print in_file.readlines()
Run Code Online (Sandbox Code Playgroud)

方案二:

with open('test.txt', 'r') as in_file:
    print in_file.readlines()
Run Code Online (Sandbox Code Playgroud)

我理解,对于Option 1,file_obj在with块之后处于关闭状态.

python

27
推荐指数
4
解决办法
2万
查看次数

如何在 mlflow.start_run() 中获取当前的 run_id ?

mlflow.active_run()不返回任何内容,所以我不能只使用 current_rui_id = mlflow.active_run().info.run_id

我必须在此构造中获取run_id ,以便能够继续在另一个块内记录参数、指标和工件,但对于同一模型:

with mlflow.start_run(run_name="test_ololo"):

    """ 
       fitting a model here ...
    """

    for name, val in metrics:
        mlflow.log_metric(name, np.float(val))

    # Log our parameters into mlflow
    for k, v in params.items():
        mlflow.log_param(key=k, value=v)

    pytorch.log_model(learn.model, f'model')
    mlflow.log_artifact('./outputs/fig.jpg')
Run Code Online (Sandbox Code Playgroud)

我必须获取当前的run_id才能在同一次运行中继续训练

with mlflow.start_run(run_id="215d3a71925a4709a9b694c45012988a"):

    """
       fit again
       log_metrics
    """

    pytorch.log_model(learn.model, f'model')
    mlflow.log_artifact('./outputs/fig2.jpg')
Run Code Online (Sandbox Code Playgroud)

python mlflow

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

Python 3:ResourceWarning:未关闭的文件&lt;_io.TextIOWrapper name ='PATH_OF_FILE'

当我使用“ python normalizer / setup.py test”在python中运行测试用例 时,出现以下异常

 ResourceWarning: unclosed file <_io.TextIOWrapper name='/Users/workspace/aiworkspace/skillset-normalization-engine/normalizer/lib/resources/skills.taxonomy' mode='r' encoding='utf-8'>
Run Code Online (Sandbox Code Playgroud)

在代码中,我正在读取一个大文件,如下所示:

def read_data_from_file(input_file):
    current_dir = os.path.realpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__)))
    file_full_path = current_dir+input_file
    data = open(file_full_path,encoding="utf-8")
    return data
Run Code Online (Sandbox Code Playgroud)

我想念什么?

python io file python-3.x

6
推荐指数
1
解决办法
4101
查看次数

在python中打开和关闭没有文件对象的文件

使用文件对象打开和关闭文件:

fp=open("ram.txt","w")
fp.close()
Run Code Online (Sandbox Code Playgroud)

如果我们想在不使用文件对象的情况下打开和关闭文件,即;

open("ram.txt","w")
Run Code Online (Sandbox Code Playgroud)

我们需要写作close("poem.txt")还是写作close()好吗?

他们都没有给出任何错误......

只编写close(),它如何理解我们引用的文件?

python

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

仅从文件中获取新行

目前我有这段代码,但它读取所有行,然后使用 while True 语句观察文件:

with open('/var/log/logfile.log') as f:
        while True:
            line = f.readline()
            if not line:
                time.sleep(1)
            else:
                print(line)
Run Code Online (Sandbox Code Playgroud)

实际上,我只需要在打开文件时已检测到的行之后添加新行 - 有人可以帮助我吗?也许还有比 while 语句更好的观看方式?

另一个问题是,在 Linux 机器上,脚本实际上锁定了文件,因此在我再次关闭脚本之前无法写入该文件。在 OS X 上它运行良好。如果有一个解决这个问题的想法也可能很好。

希望有人一直在从事类似的工作。

python logging python-2.7 python-3.x

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

列表理解中的“with”关键字?

我遇到了这种用于读取文件中的行的语法。

with open(...) as f:
    for line in f:
        <do something with line>
Run Code Online (Sandbox Code Playgroud)

假设我希望该<do something with line>行将每一行附加到列表中。有没有什么方法可以with在列表理解中使用关键字来完成此任务?或者,至少有某种方法可以在一个语句中完成我想要的事情吗?

python list-comprehension with-statement

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

使用“with dag as DAG(...)”子句创建 DAG 有好处吗

我按如下方式创建 Airflow DAG:

dag = DAG(...)
Run Code Online (Sandbox Code Playgroud)

但在多个教程和课程中,我看到他们使用with ... as这样的子句:

with DAG(...) as dag:
    # Code that will use the dag variable.
Run Code Online (Sandbox Code Playgroud)

我想这样,DAG实例将在调度程序执行代码块后被销毁,但是这样做有真正的好处吗?我找不到任何讨论此问题的文档。

airflow airflow-scheduler

4
推荐指数
1
解决办法
4283
查看次数

Scala替代蟒蛇`与`

在python中你可以避免try {} catch {} finally {}样板文件with(参见什么是python关键字"with"用于?).我记得在Scala中看到了替代方案,但我再也找不到了.

它遵循以下方针:

def using[O](r: {def close()})(doit: () => O): O = try {
  doit()
} finally {
  r.close
}

using(myWriter){() => myWriter.println("something or another")}
Run Code Online (Sandbox Code Playgroud)

它是内置于2.10,还是我需要一个单独的库?

scala

3
推荐指数
1
解决办法
202
查看次数