๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป DEV/์—ฐ๊ตฌ๋ชฉ๋ก

[์—ฐ๊ตฌ๋ชฉ๋ก] ipynb to py (ipynbํŒŒ์ผ py๋กœ ๋ณ€ํ™˜) 3๊ฐ€์ง€ ๋ฐฉ๋ฒ•

by Rising Oneโ˜… 2022. 10. 28.
728x90
๋ฐ˜์‘ํ˜•
SMALL

 


 

ํ•„์š”์„ฑ

 

jupyter notebook์„ ํ†ตํ•ด ์ž‘์—…์„ ํ•˜๋‹ค๊ฐ€ ๋ณด๋ฉด, ํŒŒ์ผ๋งˆ๋‹ค (.ipynb) ํ™•์žฅ์ž๋ฅผ ๊ฐ–๋Š”๋‹ค๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

์ด๋ฅผ (.py) ํ™•์žฅ์ž๋กœ ๋ณ€ํ™˜ํ•ด, ๋ณด๋‹ค ๋‹ค์–‘ํ•œ ์˜์—ญ์—์„œ ์ฝ”๋“œ๋ฅผ ํ™œ์šฉํ•˜๊ณ ์ž ํ•˜๋Š” ํ•„์š”์„ฑ์„ ๋งˆ์ฃผํ•  ๋•Œ๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

์ด 3๊ฐ€์ง€์˜ ๋ณ€ํ™˜ ๋ฐฉ๋ฒ•์„ ์†Œ๊ฐœํ•˜๊ณ , ํ•จ๊ป˜ ์•Œ์•„๊ฐ€๋ณด๊ณ ์ž ํ•ฉ๋‹ˆ๋‹ค.

 

  [1] Jupyter notebook์—์„œ ์ง์ ‘ ๋ณ€ํ™˜ํ•˜๊ธฐ (download as python)

  [2] %%writefile ์‚ฌ์šฉํ•˜๊ธฐ

  [3] nbconvert ๋ชจ๋“ˆ + ๋ช…๋ น์–ด ์‚ฌ์šฉํ•˜๊ธฐ


๋ฐฉ๋ฒ• [1]. Jupyter notebook์—์„œ ์ง์ ‘ ๋ณ€ํ™˜ํ•˜๊ธฐ (download as python)

 

  1. ipynb ํŒŒ์ผ์„ ์ƒ์„ฑํ•ด์ค๋‹ˆ๋‹ค.

[1-1] ์ง์ ‘ ๋ณ€ํ™˜ํ•˜๊ธฐ - ipynb ํŒŒ์ผ ์ƒ์„ฑ ํ›„, ๊ธฐ๋ณธ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•ด์ค€๋‹ค.

 

  2. File ํƒญ ํด๋ฆญ (Download as > Python) ํด๋ฆญํ•ฉ๋‹ˆ๋‹ค.
- PC์— download ๊ฒฝ๋กœ์— pyํŒŒ์ผ์ด ์ €์žฅ๋œ๋‹ค.

[1-2] ์ง์ ‘ ๋ณ€ํ™˜ํ•˜๊ธฐ - File > Download as > Python ํด๋ฆญ์‹œ pyํŒŒ์ผ์ด ์ €์žฅ๋œ๋‹ค.


 

๋ฐฉ๋ฒ• [2]. %%writefile ์‚ฌ์šฉํ•˜๊ธฐ

 

  1. Jupyter notebook cell(= ์ฝ”๋“œ์ž…๋ ฅ์ฐฝ) ๋‚ด์— ์•„๋ž˜์˜ ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ•ด์ค๋‹ˆ๋‹ค.

- ์ฝ”๋“œ์ž…๋ ฅ์ฐฝ ์ƒ๋‹จ์— ๋‹ค์Œ์˜ ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•ฉ๋‹ˆ๋‹ค.

%%writefile ํŒŒ์ผ๋ช….py

[2-1] %%writefile ์‚ฌ์šฉํ•˜๊ธฐ - ์ฝ”๋“œ ์ƒ๋‹จ์— "%%writefile ์ €์žฅํ• ํŒŒ์ผ๋ช….py"์„ ์ž…๋ ฅํ•ด์ค€ ๋’ค run(์‹คํ–‰) ์ˆ˜ํ–‰ ๊ฒฐ๊ณผ.


  2. Run (์‹คํ–‰, ctrl + enter)
- ์ฝ”๋“œ ์‹คํ–‰์„ ์ˆ˜ํ–‰ํ•ด์ฃผ๋ฉด, ipynbํŒŒ์ผ๊ณผ ๋™์ผ๊ฒฝ๋กœ์— pyํŒŒ์ผ์ด ์ €์žฅ๋จ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

 

  (+) ํŠน์ • ํฌ๋ง ๊ฒฝ๋กœ์— ์ €์žฅ์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•

- ํฌ๋งํ•˜๋Š” ๊ฒฝ๋กœ์— ์ €์žฅ์ด ๊ฐ€๋Šฅํ•˜์ง€๋งŒ, ์ด ๊ฒฝ์šฐ์— ํด๋” ์ •๋ณด๋ฅผ ์˜คํ”ˆํ•ด์•ผํ•˜๊ธฐ์— ๋ณด์•ˆ์ƒ ์œ„ํ˜‘์ด ๋  ์ˆ˜ ์žˆ์Œ์„ ์œ ์˜ํ•ฉ๋‹ˆ๋‹ค.

%%writefile ๊ฒฝ๋กœ\๊ฒฝ๋กœ\ํŒŒ์ผ๋ช….py
# %%writefile D:\test\test.py

 

๋ฐฉ๋ฒ• [3]. nbconvert ๋ชจ๋“ˆ + ๋ช…๋ น์–ด ์‚ฌ์šฉํ•˜๊ธฐ

 

  1. nbconvert ์„ค์น˜
- ipynb ํŒŒ์ผ -> py ํŒŒ์ผ (ipynb to py)์„ ์œ„ํ•ด์„œ๋Š” ๋ชจ๋“ˆ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.
- ๋ณ€ํ™˜์„ ํ•ด์ฃผ๋Š” "nbconvert" ๋ชจ๋“ˆ์„ ์„ค์น˜ํ•ฉ๋‹ˆ๋‹ค.

pip install nbconvert


  2. ๋ณ€ํ™˜ํ•ด๋ณด๊ธฐ

jupyter nbconvert --to script ํŒŒ์ผ๋ช….ipynb


  3. ์—ฌ๋Ÿฌ ํŒŒ์ผ ํ•œ ๋ฒˆ์— ๋ณ€ํ™˜ํ•˜๊ธฐ

jupyter nbconvert --to script ํŒŒ์ผ๋ช…1.ipynb ํŒŒ์ผ๋ช…2.ipynb


  4. ๊ฒฝ๋กœ ๋‚ด ๋ชจ๋“  ํŒŒ์ผ ํ•œ ๋ฒˆ์— ๋ณ€ํ™˜ํ•˜๊ธฐ (์™€์ผ๋“œ์นด๋“œ ์ด์šฉ)

jupyter nbconvert *.ipynb --to script

 

๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ^^

๋„์›€์ด ๋˜์…จ๋‹ค๋ฉด "๊ณต๊ฐ"์„,

์ถ”๊ฐ€์งˆ๋ฌธ์ด ์žˆ์œผ์‹œ๋‹ค๋ฉด "๋Œ“๊ธ€"์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”!

 

728x90
๋ฐ˜์‘ํ˜•
LIST

๋Œ“๊ธ€