Running Python in command line - python

I need to write my python commands in command line and get the outputs like
python -c a = 10
python -c print("Hello {}".format(a))
python -c import math

The best approach to your problem would be to write out a .py file and run that.
However, I can imagine that for scripting purposes you may need something like this if you cannot write a file. In that case you could separate your commands by ;, but you are going to be limited to programs without blocks, e.g.:
python3 -c "import math; a = 10; print('Hello {} {}'.format(a, math.sin(a)))"
# prints:
# Hello 10 -0.5440211108893698
but:
python3 -c "import math; a = 10; for i in range(a): print('Hello {} {}'.format(i, math.sin(i)))"
SyntaxError: invalid syntax
but again:
python3 -c "import math; a = 10; [print('Hello {} {}'.format(i, math.sin(i))) for i in range(a)]"
# prints:
# Hello 0 0.0
# Hello 1 0.8414709848078965
# Hello 2 0.9092974268256817
# Hello 3 0.1411200080598672
# Hello 4 -0.7568024953079282
# Hello 5 -0.9589242746631385
# Hello 6 -0.27941549819892586
# Hello 7 0.6569865987187891
# Hello 8 0.9893582466233818
# Hello 9 0.4121184852417566
the last one is of course bad practice and all (a side-effect in a comprehension, etc.) but kind of works.

The easiest way is to use a py file and then invoked it from command line.
Inside the name_file.py put:
a = 10
print("Hello {}".format(a))
import math
In console excute
python name_file.py
See python file

If you need run a few commands. You can run Python interpreter with writing python inside your command line. There will be >>> as a mark that all commands you write will be interpreted by interpreter.
Then you can write the commands. After each command you should press ENTER.
>>> a = 10
>>> print("Hello {}".format(a))
>>> import math

FIRST you have to add the python to your system path
1.right click on THIS PC
2.click on advanced system settings
click on environment variables
click on the path to edit
click on edit
6.search python in START MENU
7.right click on the downloaded package and click on copy full path or if your'e using python 3.6
you can reinstall and check the path from the install menu
8.add the path to the list
NOW YOU CAN DO THIS
TYPE python in the command prompt and voila
you should be able to run on the command prompt

Related

How to start REPL at the end of python script? [duplicate]

This question already has answers here:
How to drop into REPL (Read, Eval, Print, Loop) from Python code
(7 answers)
Closed last month.
How can I start REPL at the end of python script for debugging? In Node I can do something like this:
code;
code;
code;
require('repl').start(global);
Is there any python alternative?
If you execute this from the command prompt, just use -i:
➜ Desktop echo "a = 50" >> scrpt.py
➜ Desktop python -i scrpt.py
>>> a
50
this invokes Python after the script has executed.
Alternatively, just set PYTHONINSPECT to True in your script:
import os
os.environ['PYTHONINSPECT'] = 'TRUE'
Just use pdb (python debugger)
import pdb
print("some code")
x = 50
pdb.set_trace() # this will let you poke around... try "p x"
print("bye")

Pass a code of Python in a command line

Is it possible to somehow convert string which I pass via command line e.g
python myfile.py "s = list(range(1000))"
into module? And then...
#myfile.py
def printlist(s):
print(s)
?
Something like a timeit module, but with my own code.
python -m timeit -s "s = list(range(1000))" "sorted(s)"
Save the code
import sys
print(sys.argv)
as filename.py, then run python filename.py Hi there! and see what happens ;)
I'm not sure if I understand correctly, but the sys module has the attribute argv that is a list of all the arguments passed in the command line.
test.py:
#!/usr/bin/env python
import sys
for argument in sys.argv:
print(argument)
This example will print every argument passed to the script, take in mind that the first element sys.argv[0] will always be the name of the script.
$ ./test.py hello there
./test.py
hello
there
There are two options to send short code snippets similar to what you can do via the timeit module or certain other -m module option functionality and these are:
You can use either the -c option of Python e.g.:
python -c "<code here>"
Or you could use piping such as:
echo <code here> | python
You can combine multiple statements using the ; semicolon statement separator. However if you use a : such as with while or for or def or if then you cannot use the ; so there may be limited options. Possibly some clever ways around this limitation but I have yet to see them.

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

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

Is it possible to launch the Python interpreter at runtime?

I would like to know if a Python script could launch the Python interpreter at runtime, making variables accessible from the interpreter.
Let me explain myself. Let's say I have the following script:
x = 20
LaunchInterpreter() #Imaginary way to launch the Interpreter
Now, the interpreter is launched and we can play around with variables.
>>> x #x defined value by the script
20
>>> x*x
400
If you're looking for a dynamic interpreter you can use pdb. It is just a debugger though so should be used only for that purpose but can be used like in the following way;
x = 20
import pdb
pdb.set_trace()
Now you will have an interpreter and you can play around with the variables.
I don't know if this is suitable in your situation but it's the closest thing I can think of with the information provided.
Edit 1:
As stated in the comments by skishore you can also use code.interact(local=locals()) so:
x = 20
import code
code.interact(local=locals())
The -i command line option to Python forces the launching of a command interpreter after a script completes:
python --help
usage: /Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
< ... >
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
so given a file test.py that contains:
x = 7
y = "a banana"
you can launch python with the -i option to do exactly what you'd like to do.
python -i test.py
>>> x
7
>>> y
'a banana'
>>>

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

Categories