Is it possible to run first the program then wait for the input of the user in command line. e.g.
Run...
Process...
Input from the user(in command line form)...
Process...
Is it possible to run first the program then wait for the input of the user in command line. e.g.
Run...
Process...
Input from the user(in command line form)...
Process...
Just Taking Input
And that's it.
Moreover, if you want to make a list of inputs, you can do something like:
In that case, you'll be asked for data 10 times to store 9 items in a list.
Output:
You can search that list the fundamental way with something like (after making that list):
else: print "Not found."
You can replace '2' with "raw_input()" like this:
Taking Raw Data From Input File via Commandline Interface
If you want to take the input from a file you feed through commandline (which is normally what you need when doing code problems for competitions, like Google Code Jam or the ACM/IBM ICPC):
example.py
In command line interface:
Hope that helps.
It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:
For interactive user input (or piped commands or redirected input)
Use
raw_input
in Python 2.x, andinput
in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)For example:
More details can be found here.
So, for example, you might have a script that looks like this
If you saved this in
foo.py
, you could just call the script from the command line, it would print outtok tiktok
, then ask you for input. You could enterbar baz
(followed by the enter key) and it would printbar baz
. Here's what that would look like:Here,
$
represents the command-line prompt (so you don't actually type that), and I hitEnter
after typingbar baz
when it asked for input.For command-line arguments
Suppose you have a script named
foo.py
and want to call it with argumentsbar
andbaz
from the command line like(Again,
$
represents the command-line prompt.) Then, you can do that with the following in your script:Here, the variable
arg1
will contain the string'bar'
, andarg2
will contain'baz'
. The objectsys.argv
is just a list containing everything from the command line. Note thatsys.argv[0]
is the name of the script. And if, for example, you just want a single list of all the arguments, you would usesys.argv[1:]
.If you're using Python 3,
raw_input
has changed toinput
Python 3 example:
Start your script with the following line. The script will first run and then you will get the python command prompt. At this point all variables and functions will be available for interactive use and invocations.
#!/usr/bin/env python -i