简体   繁体   English

如何从 PyCharm 或其他 IDE 中的文件路径运行/重新启动 Python 脚本

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

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).我知道这个问题已经在其他地方的不同 forms 中被问过,但我没有找到我正在寻找的确切内容,或者我不理解答案(我是初学者)。

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);我正在寻找重新启动 IDE PyCharm 中的 Python 脚本,而无需重新单击“运行”按钮 - 换句话说,我想直接从该脚本中重新启动相同的条件逻辑; 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:\Users\username\filename.py对于这个问题,假设我的文件路径是 C:\Users\username\filename.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.我发现的响应只有在尝试从终端运行时才有帮助,而不是 IDE。

Thank you in advance.先感谢您。

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:您可以像这样重新运行 python 脚本,假设您想在 IDE 中再次运行相同的文件,否则使用path/file.py作为文件名:

import os
os.system(f'py {os.path.dirname(__file__)}/{os.path.basename(__file__)}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM