New course! Every coder should learn Generative AI!
Try a free lesson+ 12
[SOLVED] how to run a python file in a python program?
the code will be something like x = 1 while x < 10: if x == 5: #runfile or something like right here print("file ran") x += 1
22 Answers
+ 4
+ 10
The simplest way:
Put all the code of the python file in a main() function.
Import it as a module (e.g. import snake)
Run the main function (e.g. snake.main() )
Another way is using command line arguments but I feel like it's more for geeks.
+ 5
LONGTIEš of course you can
if your test.py has worked() and failed() inside, you can use them from the module "test"
+ 3
import os
os.system("python {.py-file}")
# or
import subprocess
subprocess.run("python {.py-file}")
+ 3
LONGTIEš
if __name__ == "__main__":
main()
+ 3
LONGTIEš of course with quotes, it's written as a text file and saved as a py file, which can be a module that you can importš
+ 3
LONGTIEš oh, if you mean the module file, yesš
+ 3
LONGTIEš what do you mean?š¤
+ 2
Flandre Scarlet
like this
import test
x = 1
y = 0
while x < 10:
if x == 5:
test.worked()
print("file ran")
y = 1
if x == 6 and y == 0:
test.failed()
break
x += 1
of course in this code failed would never be called bit it's just a example
+ 1
Q&A's leading to codes
https://www.sololearn.com/discuss/269543/?ref=app
https://www.sololearn.com/discuss/602949/?ref=app
Others: push multiline strings to interactive interpreter, exec and eval
https://code.sololearn.com/ctuNdG44xznf/?ref=app
https://code.sololearn.com/cxYMW29npKWp/?ref=app
https://code.sololearn.com/cNipu7rJdO8n/?ref=app
+ 1
playing I wanna learn how to write a script
+ 1
anyone can teach npw
+ 1
Kirk Schafer all the codes and treads you posted are about writing and running a python code in a code.
not really what i asked about, but interesting none the less.
+ 1
Flandre Scarlet so like....?
if __name__ == "__main__":
main():
print("hello world")
then
import test_main.py
x = 1
if x == 1:
test_main.main()
the output would be
hello world
+ 1
LONGTIEš I admit to being a little confused then. As far as I know we can't run another Python file here without creating something to run first and then pretending the file already existed.
(I don't mind deleting that post as too much content; seems there's no need for it)
+ 1
Kirk Schafer its ok, you can keep it there. I might need to refer to it.
+ 1
Flandre Scarlet cool, thanks again šā
0
save and open it in pythonshell .to run it use f5 key
0
į į į į š į į how would i make a main() function? would i use a class or something?
0
Flandre Scarlet but with out the quotes, right?