0

Hi have been working on a project and I have been trying to open a python file with python. So far I have learnt that it is not possible but I have learned that you can do it with cmd. I have got code that can open cmd but I can't seem to work out how to get cmd to open a python file, also if that is possible I would also like to close cmd when the python file is opened. This is what I have so far:

import os
os.system('cmd /k "Python"')
2

2 Answers 2

0
import os
os.system('cmd /k "python filename.py"') # just add your filename

You need to provide your filename to run the python file same as you do when you need to run a python file in cmd/terminal.

If you need to open the python file instead of run that file you can do:

import os
os.system('cmd /k "start notepad++ filename.py"') # open file with notepad++

or

os.system('cmd /k "more filename.py"') # to view file content in cmd

to open file with sublime:

os.system('cmd /k "subl.exe filename.py"') # make sure you have store sublime path in environment variable.
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Abhishek, I have made this code that you have shown it works really well at what it does but is runs the python code and I want to see if I can OPEN the python file.
I have read these and they are really really good and helpful. Do you think it is possible in cmd to open a python file with python(instead of things like notebook), or do you think its not possible. I would love to know.
@ Oscar, we need a text editor to view our file, the text save in file is interpreted by python. So, there no such a thing like open a file with python. we use term run a file with python which means we want that file to be interpreted by python
okay, thanks so much dude. I really apreciate it, this has been really helpful. I think I know how to do it btw. I can open cmd with python which the python types into cmd telling it to open a said .bat file which then the .bat file opens the python file. Thereby opening python with python in a way. Also i coded it so those extra applications close instintly when they open.
0

To open a file refer to the documentation at https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

But your intention is not clear. If you want to read it and evaluate it, then you might want to reconsider your approach (but it is possible).

If you want to run code dynamically checkout exec

If you want to start a sub-process in the OS then checkout https://docs.python.org/3/library/subprocess.html

Comments

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.