How to run/restart a Python script from a file path in PyCharm or other IDE

Question:

I know this question has been asked in different forms elsewhere but I’m not finding exactly what I’m looking for, or else I’m not understanding the answers (I’m beginner).

What I’m trying to do is, I assume, fairly simple.

I am looking to restart a Python script in the IDE PyCharm without re-clicking the Run button – in other words I want to restart the same script directly from a line of code, based on some conditional logic (which I have nailed down fine); so the code would be the equivalent of clicking the Run button again, except that I am trying to avoid that manual action for convenience.

For the purpose of this question, let’s say my file path is C:Usersusernamefilename.py

Would you be able to point me in the right direction?

The responses I find are helpful only if trying to run from a terminal, not an IDE.

Thank you in advance.

Asked By: Lianji

||

Answers:

You can rerun the python script like this, assuming you want to run the same file again in the IDE, else use path/file.py instead as filename:

import os
os.system(f'py {os.path.dirname(__file__)}/{os.path.basename(__file__)}')
Answered By: Mole
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.