Interactive Python like Interactive Ruby? - python

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?

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

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.

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.

You are using python 3
so you do it like this
name = input("Enter your name: ")
print("Hello " + name + ". Welcome to Python!")

Related

In Julia: How do I get the name of the currently running program?

In Python 3.6+ the following works:
import sys
print(f"Program name is {sys.argv[0]}")
Program name is C:\Program Files\JetBrains\PyCharm Community Edition 2018.1\helpers\pydev\pydevconsole.py
How do I do this in Julia?
In a Julia program file, this works:
println("Program name is ", PROGRAM_FILE)
""" Output
Program name is StackQuestion.jl
"""
In the Julia 1.0 REPL there is no output:
julia> print("The program name is ", PROGRAM_FILE)
The program name is
This should not be a problem since getting the program name is something one would typically want to do within their running program.
A useful tip from the Julia 1.0 docs relating to the program file name is:
https://docs.julialang.org/en/v1/manual/faq/#
"How do I check if the current file is being run as the main script?
When a file is run as the main script using julia file.jl one might want to activate extra functionality like command line argument handling. A way to determine that a file is run in this fashion is to check if abspath(PROGRAM_FILE) == #__FILE__ is true."

I can't run python file interactivly with terminal

I'm using OSX Mac terminal to run python 2.7.10.
for example:
I have a file called "myfile.py"
so when I want to run it on the terminal it would be like this:
python Desktop/myfile.py
However inside the file I have wrote some functions like
def myFunction(x,y):
return float(x)/y
with this method of running a python script I can not interact with my program and use myFunction to input x and y with different values every time and test myFunction properly.
Thank You,
Try passing -i before the script name
python -i myfile.py
You can learn more about what options are available by running man python.
To quote from the manual:
-i When a script is passed as first argument or the -c option
is used, enter interactive mode after executing the script
or the command. It does not read the $PYTHONSTARTUP file.
This can be useful to inspect global variables or a stack
trace when a script raises an exception.
You can use python -i script.py
This way, script.py is executed and then python enter interactive mode. In interactive mode you can use all functions, classes and variables that was defined in the script.
You can use raw_input() to do that.Your myfile.py code can look like this:
def myFunction(x,y):
return float(x)/y
x = raw_input("Please enter x value: ")
y = raw_input("Please enter y value: ")
print(myFunction(x,y))

Portable Python Not Starting Script

Noob question.
I'm trying out Portable Python, but I can't get it to load a script from the Python-Portable.exe executable. I'm running from command line:
> Python-Portable.exe hello.py
To get it to load hello.py, which I put at the same level as the exectuable and just in case, in the same level as the real python.exe executable. It starts Portable Python, shows a splash screen for a second, then shows a console window and immediately closes it.
However, if I use command line to start python.exe directly, passing it hello.py it works correctly. Two questions then -
Why doesn't it work using Python-Portable.exe?
What'd the difference between starting Python-Portable.exe and starting Python.exe directly?
EDIT: Here is hello.py, its the example used on the Portable Python website.
print("Hello world")
a = True
if a == True:
print("It is true!")
else:
print("It is false...")
b = raw_input("Enter value:")
print("Your value is")
print(b)
raw_input("Press enter to continue...")
Typo in hello.py.
Bad code is not run, and you don't get any feedback.

How do I execute a function?

I'm new to the python and i was trying to do my first python function, but unfortunately i faced some problems to get the expected result from this simple function please help me to show the output of that function. the below posted function is written in the python editor
i do not know how to call this function from the python shell to show its result.
python code:
def printme( str ):
"This prints a passed string into this function"
print str;
return;
python shell:
>>> printme("d")
>>> Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
printme("d")
NameError: name 'printme' is not defined
$ cd /path/to/your/filename.py
$ python
>>> from filename import printme
>>> printme("hello world!")
You have to load the script as you start the interpreter. From a terminal shell (like bash or zsh):
$ python2 -i script.py
>>> printme("hola")
hola
>>>
On a side note, you don't have to terminate your statements with a semicolon (if they are in their own line), neither have to append a return statement at the end of the function (since indentation and line separation are significative in Python).
If you are using any of the IDEs for python, you could actually run the program in python shell by pressing/typing the Run(F5 equivalent). If that is not the case, read along:
Save the program as test.py (or any other name) in any location of your choice.
Start python shell
>>import sys
>>sys.path
If the directory in which you saved the test.py is present in the output of sys.path, go to step 7
sys.path.append("directory address where you saved the test.py")
>>import test #note .py is removed
>>test.printme("Hello World")
sys.path is the list containing all the directories where python looks for importing modules. By adding (appending) your directory you are ensuring the test.py can be imported as module test. You can then call any functions of test.py as test.fucn()
At step 7 you could have done:
7. >>from test import printme
8. >>printme("Hello again")
If you're using the unix shell:
$ cd C:\yourpath
$ python mypythonfile.py
If you are using the interactive mode, then this:
execfile("C:\\myfolder\\myscript.py")
The long way in interactive mode, but if you prefer to set your default path:
import os
prevPath = os.getcwd() #save the default path
myPath = "C:\myPython\somepath"
os.chdir(myPath) #set your python path
execfile("myscript.py") #executes the file
#os.chdir(prevPath) will restore the default path
Or did i misunderstood your question? If you just want to run a function, it's just as simple as this..
>>> def printme(str):
print str
>>> printme("Hello world!")
Hello world!
>>>
Hope this helps!
My python knowledge is very low... , you question come from this tutorial ,I have all to write as your example on a Linux shell , and i having none problem...
>>> def printme(str):
This print .......................
print str
return
>>> printme('d')
d
how i have Understand , you problem is that you to prove working with idle console and a Linux shell without before your code to save....i think , the examples from shellfly and alKid describe gut , how can you solving your problem...
sorry about my English....

Problem with reading in parameters with special characters in Python

I have a scripts (a.py) reads in 2 parameters like this:-
#!/usr/bin/env python
import sys
username = sys.argv[1]
password = sys.argv[2]
Problem is, when I call the script with some special characters:-
a.py "Lionel" "my*password"
It gives me this error:-
/swdev/tools/python/current/linux64/bin/python: No match.
Any workaround for this?
Updated-
It has been suspected that this might be a shell issue rather than the script issue.
I thought the same too, until i tried it out on a perl script(a.pl), which works perfectly without any issue:-
#!/usr/bin/env perl
$username = $ARGV[1];
$password = $ARGV[2];
print "$username $password\n";
%a.pl "lionel" "asd*123"
==> lionel asd*123
No problem.
So i guess , this looks to me more like a PYTHON issue.
Geezzz ........
The problem is in the commands you're actually using, which are not the same as the commands you've shown us. Evidence: in Perl, the first two command-line arguments are $ARGV[0] and $ARGV[1] (the command name is $0). The Perl script you showed us wouldn't produce the output you showed us.
"No match" is a shell error message.
Copy-and-paste (don't re-type) the exact contents of your Python script, the exact command line you used to invoke it, and the exact output you got.
Some more things to watch out for:
You're invoking the script as a.py, which implies either that you're copying it to some directory in your $PATH, or that . is in your $PATH. If the latter, that's a bad idea; consider what happens if you cd info a directory that contains a (possibly malicious) command called ls. Putting . at the end of your $PATH is safer than putting it at the beginning, but I still recommend leaving it out altogether and using ./command to invoke commands in the current directory. In any case, for purposes of this exercise, please use ./a.py rather than a.py, just so we can be sure you're not picking up another a.py from elsewhere in your $PATH.
This is a long shot, but check whether you have any files in your current directory with a * character in their names. some_command asd*123 (without quotation marks) will fail if there are no matching files, but not if there happens to be a file whose name is literally "asd*123".
Another thing to try: change your Python script as follows:
#!/usr/bin/env python
print "before import sys"
import sys
print "after import sys"
username = sys.argv[1]
password = sys.argv[2]
This will tell you whether the shell is invoking your script at all.
That error comes from your shell, not from Python. Do you have a shopt -s failglob set in your .bashrc or somewhere?
/swdev/tools/python/current/linux64/bin/python: No match.
I think the problem is that the python env is not set:
Does python run at all on your machine ?

Categories