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.
Related
I'll want to know how to call a function in vs code. I read the answer to similar questions, but they don't work:
def userInput(n):
return n*n
userInput(5)
And appends nothing
def Input(n):
return n*n
And in the terminal:
from file import *
from: can't read /var/mail/file
Can somebody help me?
You are doing everything correctly in the first picture. In order to call a function in python on vs code you first have to define the function, which you did by typing def userInput(n):. If you want to see the result of your function, you should not use return, you should use print instead. Return is a keyword- so when your computer reaches the return keyword it attempts to send that value from one point in your code to another. If you want to see the result of your code, typing print (n) would work better.
Your code should look like this:
def userInput(n):
print (n * n)
userInput(5)
The code would print the result 25
Your terminal is your general way to access your operating system, so you have to tell it that you want it to interpret your Python code first.
If you want to run the file you're typing in, you have to first know the location of that file. When you type ls in your terminal, does the name of your Python file show up? If not, hover over the tab in VSCode (it's close to the top of the editor) and see what path appears. Then in your terminal type cd (short for "change directory") and then the path that you saw, minus the <your filename here>.py bit. Type ls again, and you should see your Python file. Now you can type python <your filename here>.py to run it (provided you have Python installed).
You could also run the IDLE by just typing python in your terminal. This will allow you to write your code line-by-line and immediately evaluate it, but it's easier to write in VSCode and then run it with the method I described before.
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))
I started to learn Python with learn Python the Hard Way and I am facing some issues with ex13. I would like to now if it is a mistake of mine or because of the way PyCharm works.
Basically to make the script work as the exercise suggests I saw I have to manually enter the parameters names in PyCharm with run>edit configuration
I put "first" "second" and "third"
But I would like to combine raw_input and argv so I can let the user choose the name of the parameters. Here's what I wrote:
from sys import argv
first = raw_input("First argument: ")
second = raw_input("Second argument: ")
third = raw_input("Third argument: ")
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
It runs but it returns:
ValueError: need more than 1 value to unpack
It seems that in PyCharm I have to enter manually all the script parameters ? There is no way to combine it with raw input ?
Thanks for your help.
note check out Joran's answer which shows a good combination of using command line args and prompting for user inputs. Below is a break down of what is going on:
This is expected behaviour in PyCharm to specify the parameters you want PyCharm to execute your script with. Think of it like PyCharm doing something like this:
python my_script.py
However, PyCharm does not know the arguments you want to pass, you need to provide this, so it knows how to run your script. If you look near the bottom of your PyCharm window, there is a Terminal tab. You can use that to quickly execute your script and provide args.
Secondly, the reason why you are getting the error you are getting is because you are not handling your script inputs properly when trying to use argv.
You are mixing up using raw_input, which takes in user input when your Python script is running, as opposed to argv which takes parameters in to your Python script when you run it.
So, what you are looking to actually do here, is not use raw_input, but simply argv. Here is a small demo to clarify all this:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
Now, go in to your command prompt and do this:
python my_script one two three
You will get:
The script is called: my_script.py
Your first variable is: one
Your second variable is: two
Your third variable is: three
This is a very simplified example, and you're probably going to need to add some handling of your inputs, or you're going to get a lot of errors with different inputs to your script. With that, I suggest maybe looking at argparse instead
Im not sure i understand the question ... but the code below will use the command line arguments if there are 3(or more) ... otherwise it will prompt and split the same way as the shell splits command line arguments
import shlex # shlex.split will split the string the same way that the shell would for command line args
if len(sys.argv) < 3:
args = (list(sys.argv) + shlex.split(raw_input("Enter Args:")))[:3]
else:
args = sys.argv[:3]
print "Using Args:",args
one,two,three = args
Today I managed to run my first Python script ever. I'm a newb, on Windows 7 machine.
When I run python.exe and enter following (Python is installed in C:/Python27)
import os
os.chdir('C:\\Pye\\')
from decoder import *
decode("12345")
I get the desired result in the python command prompt window so the code works fine. Then I tried to output those results to a text file, just so I don't have to copy-paste it all manually in the prompt window. After a bit of Googling (again, I'm kinda guessing what I'm doing here) I came up with this;
I wrote "a.py" script in the C:/Pye directory, and it looked like this;
from decoder import *
decode("12345")
And then I wrote a 01.py file that looked like this;
import subprocess
with open("result.txt", "w+") as output:
subprocess.call(["python", "c:/Pye/a.py"], stdout=output);
I see the result.txt gets created in the directory, but 0 bytes. Same happens if I already make an empty result.txt and execute the 01.py (I use Python Launcher).
Any ideas where am I screwing things up?
You didn't print anything in a.py. Change it to this:
from decoder import *
print(decode("12345"))
In the Python shell, it prints it automatically; but the Python shell is just a helper. In a file, you have to tell it explicitly.
When you run python and enter commands, it prints to standard out (the console by default) because you're using the shell. What is printed in the python shell is just a representation of what object is returned by that line of code. It's not actually equivalent to explicitly calling print.
When you run python with a file argument, it executes that script, line by line, without printing any variables to stdout unless you explicitly call "print()" or write directly to stdout.
Consider changing your script to use the print statement.:
print(decode("12345"))
I just want to have some ideas to know how to do that...
I have a python script that parses log files, the log name I give it as an argument so that when i want to run the script it's like that.. ( python myscript.py LOGNAME )
what I'd like to do is to have two scripts one that contains the functions and another that has only the main function so i don't know how to be able to give the argument when i run it from the second script.
here's my second script's code:
import sys
import os
path = "/myscript.py"
sys.path.append(os.path.abspath(path))
import myscript
mainFunction()
the error i have is:
script, name = argv
valueError: need more than 1 value to unpack
Python (just as most languages) will share parameters across imports and includes.
Meaning that if you do:
python mysecondscript.py heeey that will flow down into myscript.py as well.
So, check your arguments that you pass.
Script one
myscript = __import__('myscript')
myscript.mainfunction()
script two
import sys
def mainfunction():
print sys.argv
And do:
python script_one.py parameter
You should get:
["script_one.py", "parameter"]
You have several ways of doing it.
>>> execfile('filename.py')
Check the following link:
How to execute a file within the python interpreter?