반응형

https://www.acmicpc.net/problem/2133

 

2133번: 타일 채우기

3×N 크기의 벽을 2×1, 1×2 크기의 타일로 채우는 경우의 수를 구해보자.

www.acmicpc.net

문제

3×N 크기의 벽을 2×1, 1×2 크기의 타일로 채우는 경우의 수를 구해보자.

입력

첫째 줄에 N(1 ≤ N ≤ 30)이 주어진다.

출력

첫째 줄에 경우의 수를 출력한다.

 

예제 입력 1 복사

2

예제 출력 1 복사

3
"""_summary_
    타일 채우기 
    https://www.acmicpc.net/problem/2133
    문제 3×N 크기의 벽을 2×1, 1×2 크기의 타일로 채우는 경우의 수를 구해보자.
    입력 첫째 줄에 N(1 ≤ N ≤ 30)이 주어진다.
"""
n = int(input("값을 입력하세요~ : "))
tile = [0 for _ in range(31)]
tile[2] = 3
for i in range(4, n+1):
    if i%2 == 0:
        tile[i] = tile[i-2] * 3 + sum(tile[:i-2]) * 2 + 2
    else:
        tile[i] = 0

print(tile[n])




#2번째 풀이 

n = int(input())
dp = [0]*(n+1)

if n % 2 != 0:
    print(0)
else:
    dp[2] = 3
    for i in range(4, n+1, 2):
        dp[i] = dp[i-2] * 3 + 2
        for j in range(2, i-2, 2):
            dp[i] += dp[j] * 2

    print(dp[n])
반응형
반응형

[python] Python 3.11: 진정으로 즐길 수 있는 새로운 기능

https://towardsdatascience.com/python-3-11-new-features-that-you-will-truly-enjoy-9fd67882fdf

 

Python 3.11 New Features That You Will Truly Enjoy

Kudos to all the effort by volunteers across the world

towardsdatascience.com

이미지 출처: Unsplash

Python 3.11은 2022년 10월 24일에 출시되어 우리가 만져볼 수 있는 몇 가지 흥미로운 개선 사항을 제공했습니다. 여기에서 모든 PEP 의 전체 문서를 볼 수 있습니다 . 이 기사에서는 5가지와 추가로 여러분이 높이 평가할 멋진 새 기능을 제공할 것입니다.

PEP 657 : 오류 추적 로케이터

Python 3.11 이전에는 예외가 발생했을 때 오류 추적의 유일한 정보는 오류가 무엇인지 설명 하는 줄 이었습니다. 예를 들어,

x, y, z = 1 , 2 , 0
 a, b, c = 3 , 4 , 5
 결과 = (x / y / z) * (a / b / c)

이 코드는 0과 같은 나누기 때문에 오류를 발생시킵니다. X/Y by Z다음은 이치에 맞는 오류 메시지이지만 코드의 어느 부분이 이 문제를 일으켰는지 아직 모르기 때문에 정보가 아닙니다.

Python 3.11에서 우리는 이것을 보게 될 것입니다.

오류 탐지기의 도움으로 근본 원인이 Y 또는 Z가 0~~^~~ 이라는 것이 분명합니다 . 이 주석이 달린 트레이스백은 코드가 복잡해지면 더욱 강력해집니다.

PEP 673 : 자아 유형

유형 힌트의 경우 이전에는 현재 클래스 자체를 참조해야 하는 경우 아래와 같이 유형 변수 를 명시적으로 정의해야 했습니다.

이제 3.11에서는 Self 캡슐화 클래스 자체를 참조하는 유형을 사용할 수 있습니다. 이렇게 하면 유형 변수를 정의하는 번거로움이 사라집니다.

향상된 {asyncio} : 비동기 컨텍스트 관리자

비동기 프로그래밍을 사용하면 코드는 여전히 한 번에 한 단계씩 실행되지만 시스템은 다음 단계로 이동하기 전에 이 단계가 완료될 때까지 기다리지 않습니다.

파이썬에서 이것은 {asyncio}모듈에 의해 처리됩니다. 우리는 여러 비동기 작업을 생성하고 각 작업이 실행될 때까지 기다린 다음 asyncio.gather(). 예를 들어 심부름을 해보자.

 

터미널에서 실행하면 다음과 같은 결과가 나타납니다.

그러나 list 작업을 기다리기 전에 수동으로 모니터링하는 asyncio.gather것은 번거롭습니다. 새로운 기능/클래스 TaskGroup()가 3.11에 도입되었습니다.

 

TaskGroup종료 시 모든 작업을 기다리는 작업 그룹을 보유하는 컨텍스트 관리자로 기능합니다 . 또한 구문이 더 간단합니다.

PEP 654 : 예외 그룹

예외 처리를 위한 유사한 "그룹화" 기능은 3.11에 추가된 예외 그룹 입니다. 단일 예외에 래핑된 여러 일반 예외로 생각할 수 있습니다.

볼 수 있듯이 오류가 를 트리거하면 ExceptionGroup자체 패널에 표시된 두 하위 예외가 모두 발생했습니다.

처리 하기 위해 ExceptionGroup Python 3.11에는 새 키워드도 추가되었습니다 except*.

를 사용하면 except*에 래핑된 여러 오류 ExceptionGroup 가 처리됩니다. 이 기능은 여러 비동기 작업이 함께 실행되는 { asyncio } 에서 사용될 때 더 효과적입니다.

PEP 678 : 사용자 지정 예외 사항

add_note오류 처리를 위한 또 다른 훌륭한 새 기능은 사용자 지정 메시지를 추가할 수 있는 예외 메모입니다 . 예를 들어,

보너스 PEP 659 : 더 빠른 실행 속도

존경하는 가작으로 Python 3.11은 Faster CPython 이니셔티브 덕분에 이전 버전보다 10%-60% 더 빠를 것으로 예상됩니다.

결론: Python 3.11로 업그레이드해야 합니까?

때에 따라 다르지! 개인적으로 프로젝트에 사용된 특정 라이브러리가 아직 Python 3.11과 호환되지 않을 수 있으므로 프로덕션 환경을 업그레이드하지 않도록 주의 해야 합니다.

테스트해보고 싶다면 Google colab에서 테스트하는 것이 좋습니다. 다음을 실행하여 Python 버전을 3.11로 업그레이드할 수 있습니다.

!sudo apt-get 업데이트 -y 
!sudo apt-get install python3 .11
 !sudo 업데이트 대안 --install /usr/ bin /python3 python3 /usr/ bin /python3 .7  1
 !sudo 업데이트 대안 --install / usr/ bin /python3 python3 /usr/ bin /python3 .11  2

이 기사에서는 가장 흥미로운 새 기능만 살펴보았습니다. 모든 개선 사항 및 변경 사항에 대한 공식 릴리스 문서 를 확인하십시오 .

반응형
반응형

데이터 과학자를 위한 6가지 Python 팁

https://towardsdatascience.com/top-6-python-tips-for-data-scientists-4f4a25e44d15

 

Top 6 Python Tips for Data Scientists

Practical tips and tricks from my daily analytics projects

towardsdatascience.com

 

 

### 데이터 과학자를 위한 6가지 Python 팁
### Top 6 Python Tips for Data Scientists
### https://towardsdatascience.com/top-6-python-tips-for-data-scientists-4f4a25e44d15

codeString = '''a,b = 4,5; print(f"a = {a} and b = {b}"); print(f"a+b = {a+b}")'''
exec(codeString)

print("\n\n\n")


import os
import sys

#작업하는 경로(위치)가 어디인지 확인
print(os.getcwd())


exec(open("./Project/Datascientist/myFullFileName.py").read())

print("\n\n\n")

### 각각 현재 작업 디렉토리 또는 사용자 지정 디렉토리의 모든 파일을 나열합니다.
print( os.listdir() )



"""_summary_
"""
print("\n\n\n")

### 4. Code timer as a decorator 
import time
import requests

def timerWrapper(func):
    """Code the timer"""

    def timer(*args, **kwargs):
        """Start timer"""
        start = time.perf_counter()
        
        output = func(*args, **kwargs)
        
        timeElapsed = time.perf_counter() - start
        print(f"Current function: {func.__name__}\n Run Time: {timeElapsed}")
        return output

    return timer

## Func to make a request to an user-defined url
@timerWrapper
def getArtile(url):
    return requests.get(url, allow_redirects=True)

## Monitor the runTime 
if __name__ == "__main__":
    getArtile('https://towardsdatascience.com/6-sql-tricks-every-data-scientist-should-know-f84be499aea5')
    

print("\n\n\n")
    
## 이제 다른 함수의 시간을 측정 @timeWrapper하려면 함수 앞에 the를 놓는 것뿐입니다.
@timerWrapper
def getMultiplication(num):
    for val in range(num):
        print(10**(10**val))

getMultiplication(3)

Now, let’s jump right in!

  1. Dynamic execution with exec()

Dynamic Execution (Image Source)

Scenario: You inherited a Python project from a colleague, and immediately noticed that those scripts all have a whopping 5000+ lines of code. The same chunks (of code) got copied and pasted multiple times! So, is there a more efficient option to go about code reusability?

Let’s explore the exec() function in Python. Simply put, it takes in a string or object code, and execute it as shown in this example,

 
a = 4 and b = 5
a+b = 9

Even more handy? We can use exec(open().read()) to call and execute a file within the Python interpreter. For example,

 

With this powerful one-liner, data scientists can save programs that will be reused as standalone files, and execute them whenever needed within the main program. No code copying and pasting any more!

Being a cool functionality in Python, exec() has one pitfall to avoid — it does NOT return any value,

 
a = 4 and b = 5
a+b = 9
** Is the return from exec() is None? True **

As we can see, the output of the exec() function is None; hence, it cannot be used to store any values, which is equivalent to the sounce()function in R.

***Join our YouTube community 🎦 “Data Talks with Kat” 😄

 

2. Operating system commands with {os} and {shutil}

Scenario: continue from our previous tip, now you want to check out the script before executing it. Don’t bother to double-click your mouse all the way through to open up the file? No problem, you can easily achieve this in Python directly without interrupting your train of thought.

 

Here, the os.startfile() function allows users to open up any type of files, including MS documents, Excels, R and SQL scripts.

Similarly, we can also delete a FILE using os.remove(“myFullFileName.ANYFORMAT”)

or delete the entire DIRECTORY using shutil.rmtree(“folderToBeRemoved”). where {shutil} is a Python module that offers a number of high-level file operations, particularly for file copying and removal.

Therefore, if you haven’t used {os} other than os.getcwd() or os.chdir() or if the {shutil} sounds unfamiliar, it’s time to check out their documents. You will definitely find useful commands or file system methods that make your coding easier. Here lists a few of my favorites,

  • os.listdir() or os.listdir(“someDirectory”) — list all files in the currently working directory or any user-specified directory, respectively;
  • os.path.join() — automatically create a path with elements in the arguments for later use, e.g., os.path.join(‘D’, ‘Medium’, ‘New Folder’) will return
 ‘D\\Medium\\New Folder’
  • os.makedirs() — create a directory;
  • shutil.copy2(“sourcePath”, “destinationPath”) or shutil.move(“sourcePath”, “destinationPath”) — copy or cut a file respectively.

3. One-liner: Nested list comprehension to get rid of the for loops

Scenario: this “simple” task we come across is to combine several lists into one big long list,

 

Surely, we can write five nested for loops to append each sublist to the final output list. But it’s smarter to turn to nested list comprehension for the most concise way,

 

4. Timer wrapped as a decorator

Timer as a decorator (Image Source)

Scenario: while Python is recognized as one of the most effective programming languages, data scientists still need to check the runtime of our programs.

It’s not the hardest thing if we just implement a bare-bones Python timer for each function we want to monitor. However, if we code it as a decorator, we would make our timer much easier to be version-controlled and reused!

Here is how,

 

In this snippet,

  • the timer is wrapped in a timerWrapper function, which then is used as a decorator called prior to the main function;
  • The example main function is to return a request connecting to an URL, which is one of my previous blogs.

Running this code gives us the time elapsed,

Current function: getArtile
 Run Time: 1.6542516000008618Out[101]: <Response [200]>

Now, to time another function, all we need is to put the @timeWrapper in front of the function,

 
getMultiplication(3)
10
10000000000
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Current function: getMultiplication
 Run Time: 0.00014700000065204222

5. Leverage the options system to customize your display

Scenario: as data scientists, we analyze data with {pandas} and {numpy} on a daily basis. When I first learned coding in Python, I was frustrated seeing this after reading my data into the IDE,

Clearly, data display is cut off both row-wise and column-wise, and the following code can fix it,

 

Here, we are explicitly setting the maximum columns, rows and column width to display/print in the console. There are numerous customizable options and settings in {pandas}, and similar operations are also available in {numpy} for arrays and matrix,

 

6. Reproduce your machine learning model results? Set seeds!

Scenario: Due to the stochastic nature of machine learning modeling process, we have all encountered the non-deterministic aspect of machine learning. This randomness results in our difficulty reproducing the same results across different runs. Consequently, it’s challenging to figure out whether an improvement in performance metrics is a result of successful model tuning or simply a different random training/testing sample.

Luckily the reproducibility can be achieved by setting the random seed throughout your model pipeline, provided that you do it correctly! How many times have you seen questions like “Getting a different result despite random seed defined” popping up on Stack Overflow? Well, how to appropriately set seeds should be in the first page of documentations, but it took me some time to dig it out.

I found that NOT every seed is defined the same in {numpy}, {sklearn}, {tensorflow} or {torch}. Thus, it’s a best practice to use a definitive function that sets all SEEDS for all your frameworks. For example,

 

Adding this tactical reset_random_seed() function to all necessary steps of your workflow, such as train-test split, model compile/training, and interpretation, will get you half way to full reproducibility. More detailed visibility into your experiments will finish the second half!

반응형
반응형

React와 Django로 웹 서비스 뚝딱 세팅하기 (feat. Webpack, Redux, django rest framework, PWA)

http://milooy.github.io/TIL/Django/react-with-django-rest-framework.html#%E1%84%86%E1%85%A9%E1%86%A8%E1%84%91%E1%85%AD

 

[서버부터 프론트까지] React와 Django로 웹 서비스 뚝딱 세팅하기 (feat. Webpack, Redux, django rest framework

[서버부터 프론트까지] React와 Django로 웹 서비스 뚝딱 세팅하기 (feat. Webpack, Redux, django rest framework, PWA) 목표 모임 개설 사이트, 'MOGAE' 제작. Django에 Django Rest Framework를 얹어 API 서버를, react로 프론

milooy.github.io

목표

모임 개설 사이트, 'MOGAE' 제작. Django에 Django Rest Framework를 얹어 API 서버를, react로 프론트엔드를 개발합니다. 상태관리는 redux로 하며 Progressive Web App기술을 적용해 앱처럼 사용할 수 있습니다.

이를 연동하여 온전한 웹 어플리케이션을 만드는 것에 초점을 맞춘 튜토리얼입니다. (기술에 대한 설명은 하지 않습니다.)

#사용 버전

  • Python: 3.4.3
  • Django: 1.11.3
  • Django Rest Framework: 3.6.3

장고걸스 : https://tutorial.djangogirls.org/ko/django_installation/

 

Django 설치하기 · HonKit

virtualenv를 생성하려면 콘솔 창을 열고, (이전 장에서 얘기했는데, 기억나죠?) 그리고 C:\Python35\python -m venv myvenv를 실행하세요. 아마도 화면에 이렇게 보일 거에요. : command-line C:\Users\Name\djangogirls>

tutorial.djangogirls.org

https://gitter.im/DjangoGirls/tutorial

 

DjangoGirls/tutorial

This is a tutorial we are using for Django Girls workshops

gitter.im

 

@ Django 자습 : https://wikidocs.net/book/837

 

Django 자습

Django 자습, 요약, 정리 # 출처 ## 참고 서적 * Django로 배우는 쉽고 빠른 웹 개발 - 파이썬 웹 프로그래밍 * Django를 활용한 쉽고 빠른 웹 …

wikidocs.net

 

반응형
반응형

변수는 프로그래밍에서 "하나의 데이터(숫자, 문자등)를 저장할 수 있는 메모리 공간"으로, 데이터 타입에 따라 정수, 소수, 문자등을 저장할 수 있다.

변수의 이름을 정의함에 있어 일반적인 룰은 아래와 같다. 

- 파이썬에서 예약어는 사용할 수 없다.

- 변수는 하나의 문자(a letter)나 밑줄(underscore) 시작해야 한다. 

- 변수의 두번째 문자부터는 문자(letter), 숫자(number) 또는 밑줄(underscore)를 사용할 수 있다. 

- 변수는 대, 소문자을 구분한다. 

- 변수명의 타입은 값에 따라 변화한다. 

 

표준 데이터 유형

데이터 유형 할당 구분 아이템 구분 특징
숫자 Number Type      
문자 StringType "" or ''    
셋 Set Type {} , 중복제외, 순서없음
리스트 List Type [] ,  
딕셔너리 Dictionary Type {} , 키와 값으로 분리
튜플 Tuple () , 수정불가

 

 

데이터 형식 변환 (Data Type Conversion)

 

Function Description
int(x) x 값을 정수 타입으로 변환한다.
float(x) x 값을 부동 소수점 타입으로 변환한다.
complex(x) x 값을 복소수 타입으로 변환한다.
str(x) x 값을 문자 타입으로 변환한다.
repr(x) x 값을 표현식 문자 타입으로 변환한다.
eval(str) x 값이 문자 타입인지를 검증한다.
tuple(s) s를 튜플 타입으로 변환한다.
list(s) s 값을 리스트 타입으로 변환한다.
set(s) s 값을 셋 타입으로 변환한다.
dict(d) d 값을 딕셔너리 타입으로 변환한다.
frozenset(s) s 값을 고전 셋 타입으로 변환한다.
chr(x) x 값을 문자 타입으로 변환한다.
ord(x) x 값을 정수 타입으로 변환한다.
hex(x) x 값을 16진수 문자 타입으로 변환한다.
oct(x) x 값을 8진수 문자 타입으로 변환한다.

 

반응형
반응형

[python] 환경변수 관련.  os, sys

import os
import sys
 


print(" os 환경변수 environ \n")
print(" * 모든 시스템 환경 변수 ") 
print(" os.environ()  : ", os.environ)

print('')
for key, value in os.environ.items():
    print('{}: {}'.format(key, value))


print(" * 특정 시스템 환경 변수 ")    
print(" os.environ('JAVA_HOME')  : ", os.environ['JAVA_HOME'])

# 존재하지 않는 환경 변수를 가져오면, 에러는 발생하지 않고 None이 리턴
result = os.environ.get('NOT_EXISTS')
print(result)

print(" * 현재 코드가 실행되는 디렉토리까지 문자열 ")
print(" os.getcwd() : ", os.getcwd())

print(" * 현재 실행 파이썬 스크립트의 PID 출력 ")
print(" os.getpid() : ",  os.getpid() )


print(" * 현재 워킹 디렉토리 변경  ")
print(" os.chdir() : " )
print(" import os ")
print(" print(os.getcwd()) #/Users/projects/workspace ")
print(" os.chdir( os.getcwd()+'/scripts/src' ) ")
print(" print(os.getcwd()) #/Users/projects/workspace/scripts/src ")

print(" * 디렉토리 만들기 : mkdir(path[,mode]) ")
#_result = os.mkdir("test_dir")
#print(_result)


print(" * path에 존재하는 파일과 디렉토리들의 리스트 반환 ")
_result = os.listdir(".")
print(" os.listdir('.') : ",  _result )
print('')
for x in _result:
    print('{}'.format(x))

# 인자로 전달된 디렉토리를 재귀적 생성
#  - 이미 **디렉토리가 생성**되어 있는 경우나 **권한이 없어 생성할 수 없는 경우**는 **예외**발생
print(" * 디렉토리 만들기 : makedirs(path[,mode]) 이미 **디렉토리가 생성**되어 있는 경우나 **권한이 없어 생성할 수 없는 경우**는 **예외**발생")
#_result = os.makedirs("test_dir")


print(" * 하위 폴더를 for문으로 탐색 : os.walk(path) ", " 기본적으로 top-down임. bottom-up으로 하고 싶다면 ")

if __name__ == "__main__":
    root_dir = "./"
    for (root, dirs, files) in os.walk(root_dir):
        print("root : " + root)
        if len(dirs) > 0:
            for dir_name in dirs:
                print("dir: " + dir_name)

        if len(files) > 0:
            for file_name in files:
                print("file: " + file_name)

os.walk(root_dir, topdown=False)  #bottom-up으로 하고 싶다면,

print(" * 'A'+'/'+'B' 로 문자열을 return 한다. : os.path.join('A','B) ")

print(" os.path.isdir(): directory인가? ")
print(os.getcwd(), " ==> " , os.path.isdir(os.getcwd()) )

print(" os.path.abspath(path): abs 경로 반환  ")
print(" 현재 ./sketchpy_001.py 파일의 절대경로 : ", os.path.abspath("./sketchpy_001.py"))


print(" os.path.dirname(path) : 경로의 제일 뒤 빼고 반환  ")

print(" os.path.exists(path) : 지정한 path에 파일, 디렉토리가 존재하는지 유(True)/무(False) 리턴  ")
print("os.path.isfile(path)  ")
print("os.path.isdir(path)  ")
print("os.path.isabs()  ")
print("")

import glob

print( " glob.glob(os.getcwd()) : ls와 유사한 기능을한다, 정규식 사용 가능 (* ? [0-9])" )
print(" (workspace) $ ls = glob.glob(os.getcwd()+'/*'))  ")
print(" list로 return  ")
print( glob.glob(os.getcwd()))
print( glob.glob(os.getcwd() + "/*"))

print( "" )
print(" glob.iglob(path)  ")
print("    - glob.glob와 다르게 iterator로 반환  ")
print("    - list로 담지 않기 때문에 결과가 매우 많다면 유용함  ")
for i in glob.iglob(os.getcwd()+'/*'):
    print(i)
반응형
반응형

[PYTHON] 파일 인코딩 관련

 

UTF-8

UTF-8-SIG

""" 
    인코딩 정보
"""
import os
import sys 
 
 
#작업하는 경로(위치)가 어디인지 확인
#print(os.getcwd())
prePath_in = "./Project/" 
prePath_out = "./Project/" 



#1. 기본 내용적기

# 기본 텍스트 신규 입력
file = open("test.txt", "w")
file.write("내용입력")
file.close()

# 한글깨짐 방지 ENCODING UTF-8
file = open("test.txt", "w", encoding="UTF-8")
file.write("내용입력")
file.close()

# 한글깨짐 방지2 ENCODING UTF-8
# txt는 UTF-8로도 충분한데 csv는 UTF-8로만 하면 읽을땐 다른걸로 읽을 경우 깨짐 현상 발생
file = open("test.csv", "w", encoding="UTF-8-sig")
file.write("test,test,test\n")
file.write("잘되나,안된다,오된다\n")
file.close()

# 참고
# Permission denied: 'test.csv' 가 나온다
# 파일 열고 있어서 수정할 수 없다는거다. 꺼주자.

# 추가 입력
file = open("test.txt", "a")
file.write("추가 내용입력")
file.close()


# 읽기
file = open("test.txt", "r", encoding="UTF-8")
print(file.read())
file.close()

# with 함수 : open & close 포함 
with open("test.txt", "w", encoding="UTF-8") as file:
    file.write("내용입력")
with open("test.txt", "r", encoding="UTF-8") as file:
    print(file.read())
 

 

#2. print 한거 txt 파일에 넣기

# sys.stdout 함수 사용하여 log 저장하기
f = open('test.txt','w', encoding='utf-8') # 로그 저장할 file open
sys.stdout = f
print("내용입력")
sys.stdout = sys.__stdout__   # 원래의 stdout으로 복구
f.close()                     # 로그 파일 닫기

#이렇게 해도 되긴 하는데.. 프로그램이 종료 안되면 문제가 생길듯?
sys.stdout = open('test.txt','w', encoding='utf-8')
print("내용입력")
반응형
반응형

[python] psutil - Python에서 프로세스 및 시스템 모니터링을 위한 크로스 플랫폼 lib.

 

psutil(프로세스 및 시스템 유틸리티) 은 Python에서 실행 중인 프로세스  시스템 활용 (CPU, 메모리, 디스크, 네트워크, 센서) 에 대한 정보를 검색하기 위한 크로스 플랫폼 라이브러리입니다 . 주로 시스템 모니터링 , 프로파일링, 프로세스 리소스 제한  실행 중인 프로세스 관리 에 유용합니다 . ps, top, iotop, lsof, netstat, ifconfig, free 등과 같은 고전적인 UNIX 명령줄 도구에서 제공하는 많은 기능을 구현합니다 . psutil은 현재 다음 플랫폼을 지원합니다.

https://psutil.readthedocs.io/en/latest/

 

psutil documentation — psutil 5.9.5 documentation

Utility method retrieving multiple process information as a dictionary. If attrs is specified it must be a list of strings reflecting available Process class’s attribute names. Here’s a list of possible string values: 'cmdline', 'connections', 'cpu_aff

psutil.readthedocs.io

 

https://pypi.org/project/psutil/

 

psutil

Cross-platform lib for process and system monitoring in Python.

pypi.org

pip install psutil




psutil.virtual_memory()

 

반응형

+ Recent posts