1

I have a python file named main.py which looks like this:

print('hello world')

I also have a tkinkter_run.py file which looks like this:

import sys
import os
from tkinter import *
import main

window=Tk()

window.title("Running Python Script")
window.geometry('550x200')

def run():
    os.system('main.py')

btn = Button(window, text="Run your Code!", bg="blue", fg="white",command=run)
btn.grid(column=0, row=0)

window.mainloop()

When I run my tkinker_run.py file I do get a window with a Run your Code! button, however when I click that button and look the my terminal in Visual Code I get the following error:

Hello World
'main.py' is not recognized as an internal or external command,
operable program or batch file.

So it seems that Hello World is printed before I even click the Run your Code! button. I dont understand what the problem is....

8
  • @martineau What do you mean? Commented Mar 11, 2021 at 10:48
  • Is main.py in the same directory as tkinkter_run.py? Commented Mar 11, 2021 at 10:54
  • @AST Yes it is. Commented Mar 11, 2021 at 10:54
  • @TangerCity Also, Hello World is initially printed because you have called import main. Try using os.system(os.path.abspath('main.py')), just to make sure that the correct path is supplied. Commented Mar 11, 2021 at 11:10
  • @AST I get this when I click that run the Code! button C:\data\EK\Desktop\Python is not recognized as an internal or external command, operable program or batch file. Commented Mar 11, 2021 at 11:15

2 Answers 2

1

My directory name contains spaces, most shells split up the arguments by assuming they are separated by spaces. So the solution is to place the part that contains the filename of the script between double quotes.

os.system('python "c:\data\EK\Desktop\Python Microsoft Visual Studio\MM\main.py"')

This worked!

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

2 Comments

In the comments I had told the same, you mentioned it did not work? Anyway, do consider using subprocess.Popen instead, if you don't want it to block the GUI's event loop.
If the two .py files are in the same directory, you can extract name of the folder from __file__ and add it to main.py to determine a full path to it at runtime. The will allow you to avoid hardcoding the path into your code.
0

This is because os.system only accepts a command and not a filename.

You can replace this code

os.system("main.py")

Like this

os.system("python main.py")

1 Comment

I get this: Hello World python: can't open file 'main.py': [Errno 2] No such file or directory So it seems that it gets printed again before I even click the run the Code! button

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.