从GUI按钮递归调用Jupyter Notebook遇WinError206路径过长问题求助
问题:调用Jupyter Notebook时触发"文件名或扩展名过长"错误
通过GUI按钮调用Jupyter Notebook时出现以下错误:
Error: [WinError 206] Název nebo přípona souboru je příliš dlouhá
(翻译:文件名或扩展名过长)
已尝试缩短文件路径,但问题仍未解决,所用代码如下:
def execute_jupyter_script(): try: # Convert the Jupyter notebook to a Python script notebook_path = 'C:/Users/Documents/U2.ipynb' # Update with your Jupyter script path print(f"Reading notebook from path: {notebook_path}") with open(notebook_path, 'r', encoding='utf-8') as notebook_file: notebook_content = nbformat.read(notebook_file, as_version=4) python_exporter = PythonExporter() python_script, _ = python_exporter.from_notebook_node(notebook_content) # Execute the Python script result = subprocess.run(['python', '-c', python_script], stdout=subprocess.PIPE, universal_newlines=True) # Display the result in the output_text_area output_text_area.delete('1.0', tk.END) # Clear previous content output_text_area.insert(tk.END, result.stdout) except Exception as e: print(f"Error: {e}") output_text_area.delete('1.0', tk.END) output_text_area.insert(tk.END, f"Error: {e}")
解决方案
问题根源不是文件路径过长,而是你将Notebook转换后的完整Python代码作为-c参数传递给python,导致命令行参数长度超出Windows系统限制(Windows默认命令行参数上限为8191字符)。当Notebook内容较多时,生成的python_script字符串会远超这个长度,触发WinError 206。
提供两种可行解决方法:
方法一:写入临时文件再执行
避免直接传递长代码作为命令行参数,先将转换后的代码写入临时.py文件,再执行该文件:import tempfile import os def execute_jupyter_script(): try: notebook_path = 'C:/Users/Documents/U2.ipynb' print(f"Reading notebook from path: {notebook_path}") with open(notebook_path, 'r', encoding='utf-8') as notebook_file: notebook_content = nbformat.read(notebook_file, as_version=4) python_exporter = PythonExporter() python_script, _ = python_exporter.from_notebook_node(notebook_content) # 创建临时Python文件 with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, encoding='utf-8') as temp_file: temp_file.write(python_script) temp_file_path = temp_file.name # 执行临时文件 result = subprocess.run(['python', temp_file_path], stdout=subprocess.PIPE, universal_newlines=True) # 执行后删除临时文件 os.unlink(temp_file_path) # 更新GUI输出 output_text_area.delete('1.0', tk.END) output_text_area.insert(tk.END, result.stdout) except Exception as e: print(f"Error: {e}") output_text_area.delete('1.0', tk.END) output_text_area.insert(tk.END, f"Error: {e}")方法二:直接用nbconvert执行Notebook
跳过手动转换步骤,调用jupyter nbconvert命令直接执行Notebook并捕获输出,更简洁高效:def execute_jupyter_script(): try: notebook_path = 'C:/Users/Documents/U2.ipynb' # 调用nbconvert执行Notebook并获取标准输出 result = subprocess.run( ['jupyter', 'nbconvert', '--to', 'script', '--execute', notebook_path, '--stdout'], stdout=subprocess.PIPE, universal_newlines=True ) # 更新GUI输出 output_text_area.delete('1.0', tk.END) output_text_area.insert(tk.END, result.stdout) except Exception as e: print(f"Error: {e}") output_text_area.delete('1.0', tk.END) output_text_area.insert(tk.END, f"Error: {e}")
内容的提问来源于stack exchange,提问作者user22758952
相关产品推荐
相关产品推荐

