개발하자

주피터 노트북에 원시 파이썬 파일 생성

Cuire 2023. 6. 13. 22:23
반응형

주피터 노트북에 원시 파이썬 파일 생성

나는 파이썬이 처음이다. 나는 그것을 주피터 노트로 배우기 시작한다. 주피터가 지원하는 마크다운으로 내가 배운 것을 문서화할 수 있는 동시에 파이썬 코드를 테스트하는 것은 매우 유용하다.

내가 모듈/패키지로 시작하기 전까지 나는 모든 파일이 "노트북 확장자"로 끝나는 것을 알았다. 나는 주피터가 이 보기 좋은 시각화를 하기 위해서는 어떤 형식으로 파일을 저장해야 한다는 것을 이해했다.

주피터를 사용하여 원시 파이썬 파일을 만들 수 있는 솔루션이 있습니까?

이 작업을 수행하기 위해 다른 플러그인을 설치해야 해도 괜찮습니다.




ipynb를 .py 스크립트 파일로 얻은 방법은 다음과 같습니다:

파일로 이동 -> 다른 이름으로 노트북 저장 및 내보내기 -> 실행 스크립트 .py 파일이 다운로드 폴더에 다운로드됩니다. 나는 크롬 브라우저에서 주피터랩 버전 4.0.0을 실행한다.

enter image description here

You need to select all cells in the notebook to save all the contents into .py file




Another way of creating a python file and executing it from within Jupyter notebook cell is as below:

enter image description here




Another approach of adding code from jupyter notebook cells to a .py is by using the built-in Magic command %logstart.

The %writefile saves the current cell code to a .py file.

%logstart

From the Documentation

Start logging anywhere in a session.

%logstart [-o|-r|-t|-q] [log_name [log_mode]]

If no name is given, it defaults to a file named ipython_log.py in your current directory, in rotate mode (see below).

%logstart name saves to file name in backup mode. It saves your history up to that point and then continues logging.

%logstart takes a second optional parameter: logging mode. This can be one of (note that the modes are given unquoted):

append
Keep logging at the end of any existing file.

backup
Rename any existing file to name~ and start name.

global
Append to a single logfile in your home directory.

over
Overwrite any existing log.

rotate
Create rotating logs: name.1~, name.2~, etc.

Check more options in the documentation

Example:

%logstop
%logstart -ort sample.py append

The above command appends all the Jupyter notebook code to sample.py

Note: Should run in the first cell




If you created a jupyter notebook (.ipynb), and your goal is to create a python executable file (.py) from it, you can directly use the menu option from "File > Download as > Python (.py)" as shown below.

enter image description here




In order to create a python file from an existing notebook (somenotebook.ipynb), please run

jupyter nbconvert somenotebook.ipynb --to script

This will create somenotebook.py.




Actually jupyter allows to create plain-text file:

Create a new text file

Create a Text Field

Save the text file with python extension

Save with python file extension




I didn't find such option in jupyter notebook, but you can create empty *.py file and then open with jupyter. It is better then plain text, because you get colored text.


반응형