最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - %reset in script only if run through iPython? - Stack Overflow

programmeradmin5浏览0评论

I'm developing some code in Spyder on local machine. This code need to be run on a remote server through python directly.

While developing in Spyder, I used to put a %reset -f at the very beginning in order to clear all the variables (something similar to the so-called "clearvars" or "clear all" in Matlab interactive session).

But this command in pure Python has no meaning and will raise an error

$ python prepare_data.py
  File "/home/donut/code/prepare_data.py", line 8
    %reset -f
    ^
SyntaxError: invalid syntax

I would like to write something like: "if run through iPython then execute %reset -f", but are there other solutions?

I read Ignore IPython magic in python and the main answer was to pipe the whole script into a grep function in order to remove all the magic commands prior to sending it to Python. I understand that this will do the jobs, but it's a little ugly and perhaps some solutions have been introduced since?

I'm developing some code in Spyder on local machine. This code need to be run on a remote server through python directly.

While developing in Spyder, I used to put a %reset -f at the very beginning in order to clear all the variables (something similar to the so-called "clearvars" or "clear all" in Matlab interactive session).

But this command in pure Python has no meaning and will raise an error

$ python prepare_data.py
  File "/home/donut/code/prepare_data.py", line 8
    %reset -f
    ^
SyntaxError: invalid syntax

I would like to write something like: "if run through iPython then execute %reset -f", but are there other solutions?

I read Ignore IPython magic in python and the main answer was to pipe the whole script into a grep function in order to remove all the magic commands prior to sending it to Python. I understand that this will do the jobs, but it's a little ugly and perhaps some solutions have been introduced since?

Share Improve this question edited Mar 20 at 8:15 matszwecja 8,2042 gold badges13 silver badges22 bronze badges asked Mar 20 at 8:00 DonutDonut 495 bronze badges 2
  • Write your code in a way that doesn't require you to clear variables. – matszwecja Commented Mar 20 at 8:01
  • Yes I know, but sometimes when you works with interactive session, you create some additional stuff to test hypothesis... Thus it's less a "clean your code" issue than a "clean your workspace" one ^^ – Donut Commented Mar 20 at 15:37
Add a comment  | 

1 Answer 1

Reset to default 1
from IPython.core import getipython
ipython = getipython.get_ipython()
if ipython:
    ipython.run_line_magic("reset", "-f")

Tested with Python 3.12.0 and IPython 8.22.1

发布评论

评论列表(0)

  1. 暂无评论