zacty
zacty

Reputation: 109

Interactive Python like Interactive Ruby?

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

Upvotes: 3

Views: 457

Answers (4)

Adam Oudad
Adam Oudad

Reputation: 347

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.

Upvotes: 1

An0n
An0n

Reputation: 733

You are using python 3

so you do it like this

name = input("Enter your name: ")

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

Upvotes: 0

Jonathan Van Dam
Jonathan Van Dam

Reputation: 648

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.

Upvotes: 1

dbr
dbr

Reputation: 169543

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

Upvotes: 4

Related Questions