I'm trying to load a ".py" file in Python like I did with a ".rb" file in interactive Ruby. This file runs a code which asks for a user's name, and then prints "Hello (user's name), welcome!". I have searched all over but I can't quite find a solution.
I know how to do this in Ruby, but how can I do this in Python?
Ruby Code (test.rb)
print "Enter your name:"
input = gets.chomp
puts "Hello " + input + "! Welcome to Ruby!"
Python Code (test.py)
name = raw_input("What is your name? ")
print ("Hello" + (name) + "Welcome to Python!")
How I run it in interactive ruby (irb)
So how would I do the same in python?
4 Answers 4
In Python 2 execfile("test.py") is equivelant to the Ruby load "test.rb"
In Python 3 execfile has been removed probably as this isn't usually the recommended way of working. You can do exec(open("test.py").read()) but a more common workflow would be to either just run your script directly:
python test.py
or to import your test.py file as a module
import test
then you can do reload(test) to load in subsequent edits - although this is much reliable than just re-running python test.py each time for various reasons
This assumes test.py is in a directory on your PYTHONPATH (or sys.path) - typically your shells current folder is already added
Comments
You just say import file_name in the python interpreter this should help you. Then file_name.function_to_run() of course you don't have to do this step if you have the function calls at the bottom of the script it will execute everything then stop.
Comments
From the command-line
You can use the -i option for "interactive". Instead of closing when the script completes, it will give a python interpreter from which you can use the variables defined by your script.
python -i test.py
Within the interpreter
Use exec
exec(open("test.py").read())
Comments
You are using python 3
so you do it like this
name = input("Enter your name: ")
print("Hello " + name + ". Welcome to Python!")
importing modules in Python.