3

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)

enter image description here

So how would I do the same in python?

enter image description here

zacty
  • 109
  • 5

4 Answers4

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

dbr
  • 165,801
  • 69
  • 278
  • 343
1

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.

Jonathan Van Dam
  • 630
  • 9
  • 23
1

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())

Reference thread.

Adam Oudad
  • 337
  • 1
  • 9
0

You are using python 3

so you do it like this

name = input("Enter your name: ")

print("Hello " + name + ". Welcome to Python!")

An0n
  • 705
  • 6
  • 19