async function main() {
let pyodide = await loadPyodide();
// Pyodide is now ready to use...
console.log(pyodide.runPython(`
import sys
sys.version
`));
};
main();
Running Python code
Python code is run using thepyodide.runPython()function. It takes as input a string of Python code. If the code ends in an expression, it returns the result of the expression, translated to JavaScript objects (seeType translations). For example the following code will return the version string as a JavaScript string:
pyodide.runPython(`
import sys
sys.version
`);
After importing Pyodide, only packages from the standard library are available. SeeLoading packagesfor information about loading additional packages.
Complete example
Create and save a testindex.htmlpage with the following contents:
<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/pyodide/v0.27.5/full/pyodide.js"></script>
</head>
<body>
Pyodide test page <br>
Open your browser console to see Pyodide output
<script type="text/javascript">
async function main(){
let pyodide = await loadPyodide();
console.log(pyodide.runPython(`
import sys
sys.version
`));
pyodide.runPython("print(1 + 2)");
}
main();
</script>
</body>
</html>
Alternative Example
<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/pyodide/v0.27.5/full/pyodide.js"></script>
</head>
<body>
<p>
You can execute any Python code. Just enter something in the box below and
click the button.
</p>
<input id="code" value="sum([1, 2, 3, 4, 5])" />
<button onclick="evaluatePython()">Run</button>
<br />
<br />
<div>Output:</div>
<textarea id="output" style="width: 100%;" rows="6" disabled></textarea>
<script>
const output = document.getElementById("output");
const code = document.getElementById("code");
function addToOutput(s) {
output.value += ">>>" + code.value + "\n" + s + "\n";
}
output.value = "Initializing...\n";
// init Pyodide
async function main() {
let pyodide = await loadPyodide();
output.value += "Ready!\n";
return pyodide;
}
let pyodideReadyPromise = main();
async function evaluatePython() {
let pyodide = await pyodideReadyPromise;
try {
let output = pyodide.runPython(code.value);
addToOutput(output);
} catch (err) {
addToOutput(err);
}
}
</script>
</body>
</html>
Accessing Python scope from JavaScript
All functions and variables defined in the Python global scope are accessible via thepyodide.globalsobject.
For example, if you run the codex=[3,4]in Python global scope, you can access the global variablexfrom JavaScript in your browser’s developer console withpyodide.globals.get("x"). The same goes for functions and imports. SeeType translationsfor more details.
You can try it yourself in the browser console. Go to thePyodide REPL URLand type the following into the browser console:
You can assign new values to Python global variables or create new ones from Javascript.
// re-assign a new value to an existing variable
pyodide.globals.set("x", 'x will be now string');
// add the js "alert" function to the Python global scope
// this will show a browser alert if called from Python
pyodide.globals.set("alert", alert);
// add a "square" function to Python global scope
pyodide.globals.set("square", x => x*x);
// Test the new "square" Python function
pyodide.runPython("square(3)");
Accessing JavaScript scope from Python
The JavaScript scope can be accessed from Python using thejsmodule (seeImporting JavaScript objects into Python). We can use it to access global variables and functions from Python. For instance, we can directly manipulate the DOM:
import js
div = js.document.createElement("div")
div.innerHTML = "<h1>This element was created from Python</h1>"
js.document.body.prepend(div)
PyQt5를 사용하는 파이썬 스크립트를 실행 파일로 만들기 위해서는 몇 가지 단계를 거쳐야 합니다. 여기서는 가장 일반적으로 사용되는 PyInstaller 라이브러리를 이용하여 exe 파일을 만드는 방법을 설명합니다.
1. PyInstaller 설치
아직 PyInstaller가 설치되어 있지 않다면, 명령 프롬프트 또는 터미널을 열고 다음 명령어를 실행하여 설치합니다.
pip install pyinstaller
2. 실행 파일 생성
파이썬 스크립트 파일(your_script_name.py, 여기서는 파일명을 stock_tracker.py라고 가정하겠습니다)이 있는 디렉토리로 이동한 후, 다음 명령어를 실행합니다.
pyinstaller --onefile --windowed stock_tracker.py
각 옵션의 의미는 다음과 같습니다.
--onefile: 하나의 실행 파일로 모든 의존성을 묶습니다.
--windowed 또는 -w: 콘솔 창이 나타나지 않는 윈도우 애플리케이션으로 만듭니다. PyQt5 GUI 애플리케이션이므로 이 옵션을 사용하는 것이 적절합니다.
stock_tracker.py: 실행 파일로 만들 파이썬 스크립트의 이름입니다.
3. 생성된 실행 파일 확인
명령어를 실행하면 dist라는 폴더가 생성됩니다. 이 폴더 안에 stock_tracker.exe (또는 스크립트 이름에 따라 다른 이름일 수 있습니다) 파일이 생성됩니다. 이 파일이 바로 실행 가능한 파일입니다.
주의사항:
의존성 문제: PyInstaller가 자동으로 모든 필요한 의존성 라이브러리를 포함하지 못할 수 있습니다. 실행 파일 실행 시 오류가 발생한다면, 누락된 라이브러리를 확인하고 PyInstaller 옵션을 조정해야 할 수 있습니다. 예를 들어, 특정 데이터 파일이나 라이브러리를 명시적으로 포함해야 할 수도 있습니다.
바이러스 검사: 생성된 exe 파일은 때때로 백신 프로그램에 의해 오진될 수 있습니다. 이는 PyInstaller가 실행 파일을 패키징하는 방식 때문일 수 있으며, 코드 자체에는 문제가 없을 가능성이 높습니다.
plyer 알림: plyer 라이브러리를 사용하여 알림 기능을 구현했으므로, 해당 라이브러리가 제대로 작동하는 환경에서 실행해야 알림이 표시될 수 있습니다. 일부 시스템 구성에서는 알림이 제대로 표시되지 않을 수도 있습니다.
위 단계를 따르면 파이썬 스크립트를 독립적인 실행 파일로 만들 수 있습니다. 생성된 .exe 파일을 다른 윈도우 환경에서도 파이썬 설치 없이 실행할 수 있습니다.
import os
import cairosvg
# 변환할 폴더 경로
input_folder = "img"
output_folder = "output_png"
# 출력 폴더가 없으면 생성
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# img 폴더 안의 모든 SVG 파일 변환
for filename in os.listdir(input_folder):
if filename.lower().endswith(".svg"): # 확장자가 .svg인 파일만 처리
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename.replace(".svg", ".png"))
# SVG → PNG 변환
cairosvg.svg2png(url=input_path, write_to=output_path)
print(f"변환 완료: {filename} → {output_path}")
print("✅ 모든 변환이 완료되었습니다!")
📂 폴더 구조 예시
🏆 설명
img 폴더 안의 모든 .svg 파일을 찾음.
각 .svg 파일을 .png로 변환하여 output_png 폴더에 저장.
변환이 완료되면 메시지를 출력.
✅ 이 코드를 실행하면 img 폴더 안의 모든 SVG 파일이 output_png 폴더에 PNG로 변환되어 저장됩니다! 🚀