Thursday, 7 April 2022

mac brew install specific python version

 

  1. Install the required version:

     % brew install python@3.7
     % brew list | grep python
     % brew ls python@3.7
     % ls -l /usr/local/Cellar/python@3.7/3.7.8_1/bin/python3.7
    
  2. Add a soft link to /usr/local/bin/:

     % ln -s /usr/local/Cellar/python@3.7/3.7.8_1/bin/python3.7 /usr/local/bin/python3.7
     % python3.7 -V
    
  3. Create a Python virtual environment:

     % python3.7 -m venv venv37
    
  4. Enter the virtual environment:

     % source venv37/bin/activate
    
  5. Exit the virtual environment:

     % deactivate

使用 virtualenv 建立 python 虛擬環境

安裝

pip install virtualenv

建立名為 venv 虛擬環境

virtualenv --python=/opt/python-3.6/bin/python venv

不指定路徑,直接使用版本

virtualenv venv --python=python2.7
virtualenv venv --python=python3.5
virtualenv venv --python=python3.6

若成功目錄底下會出現對應資料夾

使用虛擬環境

Linux / macOS

$ source ./venv/bin/activate

Windows

.\venv\Scripts\activate.bat

離開

deactivate 


from: https://blog.intemotech.com/%E4%BD%BF%E7%94%A8-virtualenv-%E5%BB%BA%E7%AB%8B-python-%E8%99%9B%E6%93%AC%E7%92%B0%E5%A2%83/

Monday, 21 March 2022

pyenv install 3.9 BUILD FAILED (OS X 12.0.1 using python-build 20180424)

# Install x86 homebrew

arch -x86_64 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

alias ibrew="arch -x86_64 /usr/local/bin/brew"


# Install Python 3.9

$ brew install python@3.9


from: https://qiita.com/tsuu/items/50e09d64f5afb5f5b827

Wednesday, 16 March 2022

Python: make a derived class into a singleton (Abstract method)

My Code:

# singleton.py
class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

# base.py
from abc import ABC, abstractmethod

class Base(ABC):
    @abstractmethod
    def run(self, value):
        pass

# foo.py
from base import Base
from singleton import Singleton

class Foo(Base, metaclass=Singleton):
    def run(self, value):
        print(value)

# main.py
from foo import Foo

f1 = Foo()
print(f1)
f1.run(42)
f2 = Foo()
print(f2) 

f2.run(24) 

As the error text already says, the metaclass of Foo must be a metaclass that is compatible with the base class metaclass (=ABCMeta). This means that Singleton must also inherit from ABCMeta.

New Code:

# singleton.py

from abc import ABCMeta

class Singleton(ABCMeta):
    # ...

# bar.py
from base import Base

class Bar(Base):
    def run(self, value):
        print(value)

# main.py
from foo import Foo
from bar import Bar

f1 = Foo()
print(f1)
f1.run(42)
f2 = Foo()
print(f2)
f2.run(34)

b1 = Bar()
print(b1)
b1.run(12)
b2 = Bar()
print(b2)
b2.run(21)

Output:

<foo.Foo object at 0x000001D4D512BE48>
42
<foo.Foo object at 0x000001D4D512BE48>
34
<bar.Bar object at 0x000001D4D512B0B8>
12
<bar.Bar object at 0x000001D4D512BEF0>
21

So Foo is a singleton and Bar isn't.


from: https://stackoverflow.com/questions/63373883/python-make-a-derived-class-into-a-singleton

Saturday, 5 March 2022

How to measure elapsed time in Python?

 Measuring time in seconds:

from timeit import default_timer as timer
from datetime import timedelta

start = timer()

# ....
# (your code runs here)
# ...

end = timer()
print(timedelta(seconds=end-start))

Output:

0:00:01.946339


from: https://stackoverflow.com/questions/7370801/how-to-measure-elapsed-time-in-python

Tuesday, 22 February 2022

How to get all dates (month, day and year) between two dates in python?

 You don't have to reinvent the wheel. Just parse the strings into datetime objects and let python do the math for you:

from dateutil import rrule
from datetime import datetime

a = '20120525'
b = '20120627'

for dt in rrule.rrule(rrule.DAILY,
                      dtstart=datetime.strptime(a, '%Y%m%d'),
                      until=datetime.strptime(b, '%Y%m%d')):
    print dt.strftime('%Y%m%d')

prints

20120525
20120526
2012052720120625
20120626
20120627


from: https://stackoverflow.com/questions/11317378/how-to-get-all-dates-month-day-and-year-between-two-dates-in-python

Saturday, 19 February 2022

Locust - Running tests in a debugger in pycharm

Remember to checked the [Gevent compatible] in the debugger setting.


Running Locust in a debugger is extremely useful when developing your tests. Among other things, you can examine a particular response or check some User instance variable.

But debuggers sometimes have issues with complex gevent-applications like Locust, and there is a lot going on in the framework itself that you probably arent interested in. To simplify this, Locust provides a method called run_single_user:

Note that this is fairly new feature, and the api is subject to change.

from locust import HttpUser, task, run_single_user


class QuickstartUser(HttpUser):
    host = "http://localhost"

    @task
    def hello_world(self):
        with self.client.get("/hello", catch_response=True) as resp:
            pass  # maybe set a breakpoint here to analyze the resp object?


# if launched directly, e.g. "python3 debugging.py", not "locust -f debugging.py"
if __name__ == "__main__":
    run_single_user(QuickstartUser)

It implicitly registeres an event handler for the request event to print some stats about every request made:

type    name                                           resp_ms exception
GET     /hello                                         38      ConnectionRefusedError(61, 'Connection refused')
GET     /hello                                         4       ConnectionRefusedError(61, 'Connection refused')

You can configure exactly what is printed by specifying parameters to run_single_user.

Make sure you have enabled gevent in your debugger settings. In VS Code’s launch.json it looks like this:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "gevent": true
        }
    ]
}

There is a similar setting in PyChar


from: https://docs.locust.io/en/latest/running-in-debugger.html