小编use*_*332的帖子

Python-通过Shell脚本激活conda env

我希望运行一个简单的Shell脚本来简化某些conda环境的管理。conda activatelinuxos中通过os 激活conda环境在shell中工作正常,但在shell脚本中却存在问题。有人能为我指出正确的方向的原因吗?

重复该问题的示例:

# default conda env
$ conda info|egrep "conda version|active environment"
     active environment : base
          conda version : 4.6.9

# activate new env to prove that it works
$ conda activate scratch
$ conda info|egrep "conda version|active environment"
     active environment : scratch
          conda version : 4.6.9

# revert back to my original conda env
$ conda activate base 

$ cat shell_script.sh
#!/bin/bash
conda activate scratch

# run shell script - this will produce …
Run Code Online (Sandbox Code Playgroud)

python python-3.x conda

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

我可以conda安装Python的alpha或beta版本吗?

在撰写本文时,3.8.0a4python的alpha版本可用。我想在conda env成为GA之前对其进行一些测试(出于教育目的和满足某些好奇心)。

尝试conda安装3.8时出现PackagesNotFoundError错误。是仅通过conda通道无法使用python的alpha / beta版本,还是可能找到一个替代的conda通道?

我知道最新版本可以在python.org上的下载/发行版中找到,但实际上希望尽可能在conda频道中提供。

python conda

7
推荐指数
1
解决办法
1353
查看次数

使用 argparse 进行 Python 单元测试

我正在尝试将 unittest 与使用 argparse 模块并遇到一些困难的程序一起使用。我参考了这篇有用的帖子作为起点,但显然我仍然遗漏了一些东西。

这是基本程序:

#arg_test.py
import sys
import argparse


class Thingy:
    def __init__(self, name):
        self.name = name

    def parse_args(args):
        parser = argparse.ArgumentParser(description='description here')
        parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1')
        parser.add_argument('-a', '--arg1', required=True, help='this is for arg1')
        parser.add_argument('-b', '--arg2', required=True, help='this is for arg2')
        return parser.parse_args()


def main():
    parser = Thingy.parse_args(sys.argv[1:])
    print('the args are: {}'.format(parser))
    if parser.arg1:
        print('the value of arg1 is : {}'.format(parser.arg1))
    if parser.arg2:
        print('the value of arg2 is : {}'.format(parser.arg2))


if __name__ == '__main__':
    main() …
Run Code Online (Sandbox Code Playgroud)

python unit-testing argparse python-3.x

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

Ubuntu 服务器 - 无法连接到 github

我根本无法从新安装的 Ubuntu 服务器上的命令行访问 github。Ping 和 curl github 失败,但对其他主机工作正常。

操作系统:Ubuntu 22.04.1 LTS

Ping 测试

# google
ping -c3 google.com
PING google.com(ord37s32-in-x0e.1e100.net (2607:f8b0:4009:808::200e)) 56 data bytes
64 bytes from ord31s21-in-x0e.1e100.net (2607:f8b0:4009:808::200e): icmp_seq=1 ttl=115 time=16.6 ms
64 bytes from ord37s32-in-x0e.1e100.net (2607:f8b0:4009:808::200e): icmp_seq=2 ttl=115 time=15.2 ms
64 bytes from ord37s32-in-x0e.1e100.net (2607:f8b0:4009:808::200e): icmp_seq=3 ttl=115 time=10.9 ms

--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2004ms
rtt min/avg/max/mdev = 10.914/14.210/16.553/2.398 ms

# github - fails with 'Destination Host Unreachable'
ping …
Run Code Online (Sandbox Code Playgroud)

ubuntu github

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

利用 Python f 字符串和 Yaml 文件?

如果我有一个 yaml 文件,其中包含一个带有括号符号 {} 的字符串,与 python f 字符串配合使用,那么如何在此处利用 f 字符串插值?以这个简单的 yaml 文件为例:

# tmp.yaml
k1: val1
k2: val2 as well as {x}
Run Code Online (Sandbox Code Playgroud)

如果x = 'val3',我希望 k2 的值能够反映val2 as well as val3

# app.py
x = 'val3'
with open('tmp.yaml', 'rt') as f:
    conf = yaml.safe_load(f)

print(conf)
{'k1': 'val1', 'k2': 'val2 as well as {x}'}
Run Code Online (Sandbox Code Playgroud)

这可以通过格式字符串很容易地完成......

print(conf['k2'].format(x=x))
val2 as well as val3
Run Code Online (Sandbox Code Playgroud)

但如何对 f 字符串执行同样的操作呢?

python yaml python-3.6 f-string

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

Pytest 嘲讽补丁 - 如何排除故障?

我在使用模拟补丁时遇到了我认为的常见问题,因为我无法找出正确的补丁。

我有两个问题希望得到帮助。

  1. 关于如何解决以下示例中的特定问题的想法
  2. 并且可能是最重要的关于如何最好地解决“我该修补哪一件事”问题的专业提示/指针/想法/建议。我遇到的问题是,在没有完全了解修补工作原理的情况下,我真的不知道我应该寻找什么并发现自己在玩猜谜游戏。

使用pyarrow它的一个例子目前让我感到痛苦:

我的模块.py

import pyarrow

class HdfsSearch:
    def __init__(self):
        self.fs = self._connect()

    def _connect(self) -> object:
        return pyarrow.hdfs.connect(driver="libhdfs")

    def search(self, path: str):
        return self.fs.ls(path=path)
Run Code Online (Sandbox Code Playgroud)

测试模块.py

import pyarrow
import pytest

from mymodule import HdfsSearch

@pytest.fixture()
def hdfs_connection_fixture(mocker):
    mocker.patch("pyarrow.hdfs.connect")
    yield HdfsSearch()

def test_hdfs_connection(hdfs_connection_fixture):
    pyarrow.hdfs.connect.assert_called_once() # <-- succeeds

def test_hdfs_search(hdfs_connection_fixture):
    hdfs_connection_fixture.search(".")
    pyarrow.hdfs.HadoopFileSystem.ls.assert_called_once() # <-- fails
Run Code Online (Sandbox Code Playgroud)

pytest 输出:

$ python -m pytest --verbose test_module.py
=========================================================================================================== test session starts ============================================================================================================
platform linux -- Python 3.7.4, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 …
Run Code Online (Sandbox Code Playgroud)

python mocking pytest pyarrow

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

Curl和Python请求(get)报告不同的http状态代码

我编写了一个python脚本来验证来自主机的url连接.在Linux中报告成功(http 200)的内容在curlpython(3.6)requests模块中报告为403 .

我希望有人能帮我理解报告的http状态代码中的差异吗?

来自Linux命令行的卷曲....

$ curl -ILs https://www.h2o.ai|egrep ^HTTP
HTTP/1.1 200 OK
Run Code Online (Sandbox Code Playgroud)

Python请求模块.....

>>> import requests
>>> url = 'https://www.h2o.ai'
>>> r = requests.get(url, verify=True, timeout=3)
>>> r.status_code
403
>>> requests.packages.urllib3.disable_warnings()
>>> r = requests.get(url, verify=False, timeout=3)
>>> r.status_code
403
Run Code Online (Sandbox Code Playgroud)

python curl python-3.x python-requests

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

带下划线的 Scala 字符串插值

我是 Scala 的新手,所以请随时为我指出文档的方向,但我无法在我的研究中找到这个问题的答案。

我将scala 2.11.8 与 Spark2.2 一起使用并尝试使用插值创建一个包含 dateString1_dateString2(带下划线)的动态字符串,但存在一些问题。

val startDt = "20180405" 
val endDt = "20180505"
Run Code Online (Sandbox Code Playgroud)

这似乎有效:

s"$startDt$endDt"
res62: String = 2018040520180505
Run Code Online (Sandbox Code Playgroud)

但这失败了:

s"$startDt_$endDt"
<console>:27: error: not found: value startDt_
       s"$startDt_$endDt"
          ^
Run Code Online (Sandbox Code Playgroud)

我希望这个带有转义的简单解决方法可以工作,但不会产生预期的结果:

s"$startDt\\_$endDt"
res2: String = 20180405\_20180505
Run Code Online (Sandbox Code Playgroud)

请注意,这个问题不同于Why can't _ be used inside of string interpolation? 因为这个问题希望找到一个可行的字符串插值解决方案,而上一个问题则更侧重于 Scala 内部。

scala string-interpolation scala-2.11 apache-spark-2.2

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

Elasticsearch Spark 解析问题 - 无法解析字段 [Y] 的值 [X]

我正在使用 Spark 2.3 (Pyspark) 从 Elasticsearch 6.6 索引读取数据。
Spark 作业正在尝试创建一个df,但由于解析问题而失败:

火花代码:

df = spark.read.format("org.elasticsearch.spark.sql").option("es.resource.read", index_name).option("es.nodes", hosts).load()

错误信息:

org.elasticsearch.hadoop.rest.EsHadoopParsingException: Cannot parse value [2019/05/06 19:31:21] for field [GenerateTime]

我相信这部分是由于源日期格式不是公认的ISO 8601格式。

此外,在阅读时间/日期映射文档时,我了解这可以通过创建映射来解决,但这只会影响新索引,而不会更改历史索引的映射。

题:

有没有办法解决这个问题,以便我可以通过 Spark从历史索引中成功读取(例如,在可能需要的任何映射更改之前)?我也尝试过,.option("es.mapping.date.rich", False)但没有任何运气。

elasticsearch apache-spark pyspark

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

当同一个 POST 在 Postman 中正常工作时,如何解决 Python 请求 POST 失败的问题?

当发出在 Postman 中工作正常的 POST 请求时,我继续从 python 请求中收到非常通用、无用的错误消息。

无论我尝试什么,我都会继续收到两条错误消息之一。请注意,调用的 python 脚本没有155 行,有效负载也不包含字母“u”:

{"error":{"detail":"SyntaxError: Unexpected token: u (sys_script_include.d2426c9ec0a8016501958bf2ac79c775.script; line 155)","message":"Unexpected token: u"},"status":"failure"}

{"error":{"message":"Unexpected token: u","detail":"SyntaxError: Unexpected token: u (sys_script_include.d2426c9ec0a8016501958bf2ac79c775.script; line 155)"},"status":"failure"}
Run Code Online (Sandbox Code Playgroud)

Postman中,参数会被正确解释,然后附加到 url 中,例如:

https://areallylongurl?params={"catalogItem": "Req Name"}
Run Code Online (Sandbox Code Playgroud)

Python请求中,我尝试了各种组合,但没有运气。

payload = {"params": '{"catalogItem": "Req Name"}'}
response = requests.post(url, headers=headers, json=payload, verify=False)
response = requests.post(url, headers=headers, json=json.dumps(payload), verify=False)
response = requests.post(url, headers=headers, data=payload, verify=False)
response = requests.post(url, headers=headers, data=json.dumps(payload), verify=False)
Run Code Online (Sandbox Code Playgroud)

通过使用这个非常有用的 SO 答案,我能够进一步分析请求库如何解释我提供的有效负载,但我仍然不确定如何解释这个通用错误消息,或者原因可能是什么。

有谁知道根本问题可能是什么?请注意,我可以从此 …

python python-3.x python-requests

2
推荐指数
1
解决办法
2742
查看次数

Python3有助于确定动态创建列表的大多数pythonic方法

寻求专家的帮助,以帮助我在创建的程序中做出正确的选择.创建列表的两种方法中哪一种看起来更像Pythonic并且对您可读?或者,有没有更好的方法可以做到这一点?

方法#1 - 列表理解

def test_func(*args):
    s = 'Country name: United {nm}'
    l = [s.format(nm='States') if x is 'us' 
         else s.format(nm='Arab Emirates') if x is 'uae'
         else s.format(nm='Kingdom') if x is 'uk' 
         else 'Unknown' for x in args]
    return l

# execute
test_func('us', 'uk', 'uae')

# results
['Country name: United States',
 'Country name: United Kingdom',
 'Country name: United Arab Emirates']
Run Code Online (Sandbox Code Playgroud)

方法#2 - for循环

def test_func(*args):
    s = 'Country name: United {nm}'
    l = []
    for arg in args:
        if arg …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension python-3.x

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