Can't run a python program in terminal? [Mac OSX] - python

I'm trying to execute a python program from Terminal but it isn't working.
Something like:
x = 5
Then typing:
UserName:Documents UserName$ python simple.py
Outputs:
UserName:Documents UserName$
Without actually executing/opening the file.
But if I have a program like:
x = input('Something: ')
Then it shows up in terminal, such as:
UserName:Documents UserName$ python simple.py
Something:
Probably a silly question, but been trying to fix it for the last 1.5 hours and can't find a workable solution.

The short program
x = 5
gets run and then Python exits back to the command line. No problem there, it all works correctly. If you want to stay inside the interpreter, start your program with
python -i simple.py
When running that, you will get the usual interpreter prompt after it is finished:
>>>
and you can see it did run, because x got the expected value:
>>> x
5
>>> x*x*x*x/(x+x+x-x/x)-x/x-x/x
42
Also, from inside the interpreter, you can load-and-run your file again:
>>> execfile('simple.py')
>>> x
5
See Bojan Nikolic's Running Python Programs from the Command-line for a number of other startup options.

It looks like it is working exactly as written... but maybe not as intended... The input prompt asks you to enter a value...
maybe you want to add a print so that you get a feedback that your program does something:
x = input('Something: ')
print(x)
if you are using python 2.x:
x = raw_input('Something: ')
print x
Then, on the prompt, input a value and press enter

Related

Python 3 input() function not allowing input

I haven't really ran into many issues with python but I'm working on a side project and the input() function wasn't working. I created a new file to test out a simple input() function and the same thing happened, the program doesn't take any input and it instead seems to take in the pyenv version or something? Anyone know how to fix this?
# Taking input from the user
name = input("Enter your name")
# Print input
print("Hello", name)
Pasted output from terminal:
Enter your namepyenv shell 2.7.18
Hello pyenv shell 2.7.18

creating python code on IDLE then using it in macOS terminal

I'm wondering how I can utilize my code on IDLE to work within the macOS Terminal.
For example, I created a function such as:
def multiplication_by_2(x): return 2 * x
and saved the .py file in a desktop folder.
I want to use terminal to test out various cases such as multipication_by_2(100) etc, however I am unsure about which commands to enter in terminal to achieve this.
Any direction toward this would be helpful. Thank you.
Try this at the end of the code:
number = int(str(input("Enter the number you would like to multiply by 2: ")))
multiplication_by_2(number)
This way, you get user input. Then, in the terminal:
$ python3 <filename>.py
Which should produce the output:
Enter the number you would like to multiply: <your input, ex. 100>
200
Hope that solved it!
If you are asking how to send arguments to your program through the command line, python's sys library has a list named argv that holds arguments passed from the command line. Add this to your python file:
from sys import argv
for argument in argv:
print(multipication_by_2(int(argument))) # All arguments are strings by default
Then in the command line, do python file_name.py 20 50 1 and any other number you might want to try, and the program will print its double.
Note: If your command line says python doesn't exist, try python3.

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

My mac terminal can't run python functions

I've tried to run multiple python functions on mac terminal and they all return syntax error, for this program
def spam():
print "R"
spam()
it returned the error:
./test.py: line 1: syntax error near unexpected token `('
./test.py: line 1: `def spam():'
this is really the simplest function I could find.
Just to be clear terminal is running the rest of the program but it can't handle functions.
#!/usr/bin/python
import math
number = int(raw_input("What's your surd?"))
print type(number)
#Just to let us know what the input is
if type(number) == int:
print "Number is an integer"
else:
print "Please enter a number"
value = math.sqrt(number)
#Takes the number and square roots it
new_value = int(value)
#Turns square root of number into an integer
if type(new_value) == int:
print "Surd can be simplified"
print new_value
else:
print "Surd cannot be simplified"
print value
This program runs fine even if it is a bit buggy at the moment but the following program returns the same error as the previous function.
# define a function
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
num = int(input("What's your number? "))
print_factors(num)
Why terminal is returning a syntax error where there isn't one?
The problem here (at least for that first example) is that you're not using a python interpreter. The terminal is using a bash interpreter for your python code and getting very confused. Use a command like this to execute your code python spam.py . Or first enter the python command interpreter by running python, then entering your code in the command line interpreter.
What might be even easier while getting started is to get an IDE like PyCharm (https://www.jetbrains.com/pycharm/) and running through a couple of their tutorials to get the feel of it.
Your issue is that your shell doesn't know you are running a Python script. You need to make it clear that you should be using the Python interpreter. You can either do this by:
1) Call python test.py at your terminal.
2) Add #!/usr/bin/python at the top of your Python script (you may need to alter the path to the Python executable on your system). Make the script executable, and call ./test.py at your terminal.
The benefits of 2) are that you know what version of Python you will be running your script with (Python 2.x in your case?).
Method 1) will use whatever Python version is encountered first in your PATH, which may be Python 3 or Python 2, depending on whether you have installed Python 3 at some point. The code you have written will work with Python 2.7, but not Python 3.x. Of course you can always explicitly call python2.7 ./test.py.

Syntax error in Python IDLE (Mac OS X) because of indentation

I'm assuming this is going to be stupidly easy to answer, yet I've searched all over and can't find an answer. I'm learning Python and trying to run some very simple code, but I keep getting a syntax error any time I try to do something after an indented block. For example:
x = [1,2,3];
for i in x:
print(i);
print('finished');
When I run this code, I get a syntax error on the print('finished') part. Any time I try to run anything by unindenting after a block like a loop or if statement, I get this error. I'm running Python 3.2.3 in IDLE on Mac OS X Lion.
UPDATE: seems this wasn't as easy as I thought and maybe I'm trying to get something to work that is pointless. I guess the shell only runs multiline statements when you're running a block that indents, but the moment you get back to the top level it executes the statements. Since I'll usually be working with files, most likely in Django, won't matter in the end. Thanks for all the amazingly fast responses though.
At least the python interactive interpreter on my Ubuntu system requires a newline to end the block:
>>> x = [1,2,3];
>>> for i in x:
... print(i);
... print('finished');
File "<stdin>", line 3
print('finished');
^
SyntaxError: invalid syntax
>>> x = [1,2,3];
>>> for i in x:
... print(i);
...
1
2
3
>>> print('finished');
finished
Funny enough, the python interpreter does not require the blank line when run on scripts:
$ cat broken.py
#!/usr/bin/python
x = [1,2,3];
for i in x:
print(i);
print('finished');
$ ./broken.py
1
2
3
finished
$
Take out all your semicolons.
x = [1,2,3]
for i in x:
print(i)
print('finished')
Insert a newline after print(i) (also on windows)
x = [1, 2, 3]
for i in x:
print(i)
print('finished')
Are you trying to enter this code in IDLE's default Python Shell window? You are better off opening an IDLE editor window (menu item File -> New Window) and running the code from there (menu item Run -> Run Module). Indenting in the shell window can get confusing and it is difficult to correct mistakes.

Categories