0

I have a single python script with many thousands of lines of code. I would like to run smaller chunks of the script, say a few hundred lines, to make sure they are working unitarily.

I'm using Anaconda Prompt with Anaconda 3 on Windows 10 to run my code and for some reason, running python and pasting chunks of code into the prompt is very slow. To get around having to wait for the slow paste into Anaconda Prompt, I was thinking it could be beneficial if I could run only just a portion of the code from the command line.

I've considered turning each chunk into a function but the issue is I have to import and that's not from the command line. Also, each really isn't a function per se.

EDIT: A good point was brought up for how to run a function from the command line making the above statement untrue. But again each of these sections isn't exactly a function in my opinion.

1
  • if you will run one part of code then you may get error that it can't find variable which you created in other part of code. Commented Jul 12, 2019 at 0:02

2 Answers 2

2

Sure. Assuming you're in a POSIX-style shell and you want to run, say, lines 100 to 400, you can use sed

sed -n '100,400 p' my_python_file.py | python

You can read all about the sed command in this tutorial. If you're on Windows, you can use the Linux subsystem or Cygwin to do the same.

Sign up to request clarification or add additional context in comments.

2 Comments

That is evil... I like it :D
I'm using Anaconda Prompt with Anaconda 3. It isn't POSIX natively but I found this A way to give it Linux commands. Will try this. Thanks for your suggestion!
1

If you split into functions, then you can do this to run from the shell.

python -c "import bigfile; print(bigfile.func(arg1, arg2, ...))"

1 Comment

Hey fizzybear, I really appreciate your answer! This is one possible workaround and I like that I could run it from the command line. However, I did say I don't want to make my code snippets into functions. This would mean a lot of extra time spent that I would like to avoid if possible. Is there a similar solution that doesn't require importing the whole script or turning my snippets into functions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.