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

1
  • 1
    Read about importing modules in Python. Commented Feb 4, 2018 at 4:19

4 Answers 4

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

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

Comments

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.

Comments

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.

Comments

0

You are using python 3

so you do it like this

name = input("Enter your name: ")

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

1 Comment

how does this answer the question??

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.