fungsi Copy to Clipboard tidak berfungsi di skrip berikut yang berjalan di google colab,…
- User
fungsi Copy to Clipboard tidak berfungsi di skrip berikut yang berjalan di google colab, coba dimodifikasi
import IPython from IPython.display import clear_output, display, HTML import re
Start the Jupyter Notebook server in the background
!nohup python3 -m notebook --allow-root > output.log & clear_output()
Wait for the server to start up
import time time.sleep(9)
Read the log file line by line
token = None with open("/content/output.log", "r") as f: for line in f: # Extract the token if found match = re.search(r"token=(\w+)", line) if match: token = match.group(1) break # Stop after finding the first token
Function to render Copy to Clipboard button
def render_copy_button(token): display(HTML(''' Token: {token} Copy to Clipboard function copyToClipboard() {{ var copyText = “{token}”; var textarea = document.createElement(“textarea”); textarea.value = copyText; document.body.appendChild(textarea); textarea.select(); document.execCommand(“copy”); document.body.removeChild(textarea); alert(“Token copied to clipboard!”); }} '''.format(token=token)))
If token found, render the button
if token: render_copy_button(token) else: print("Token not found in the log file.")
- Assistant
Masalah yang ada pada skrip tersebut terletak pada penggunaan tanda kutip ganda yang salah dalam HTML dan JavaScript yang menyebabkan fungsi "Copy to Clipboard" tidak berfungsi dengan benar. Berikut adalah skrip yang sudah dimodifikasi untuk memperbaiki masalah tersebut:
import IPython from IPython.display import clear_output, display, HTML import re # Start the Jupyter Notebook server in the background !nohup python3 -m notebook --allow-root > output.log & clear_output() # Wait for the server to start up import time time.sleep(9) # Read the log file line by line token = None with open("/content/output.log", "r") as f: for line in f: # Extract the token if found match = re.search(r"token=(\w+)", line) if match: token = match.group(1) break # Stop after finding the first token # Function to render Copy to Clipboard button def render_copy_button(token): display(HTML(''' <div> <p>Token: {token}</p> <button onclick="copyToClipboard()">Copy to Clipboard</button> </div> <script> function copyToClipboard() {{ var copyText = "{token}"; var textarea = document.createElement("textarea"); textarea.value = copyText; document.body.appendChild(textarea); textarea.select(); document.execCommand("copy"); document.body.removeChild(textarea); alert("Token copied to clipboard!"); }} </script> '''.format(token=token))) # If token found, render the button if token: render_copy_button(token) else: print("Token not found in the log file.")