How to pass a String sentence as Command Line Argument - python

The following code takes single String values which can be retrieved on the Python side. How can one do this with a sentence String with spaces?
from sys import argv
script, firstargument = argv
print "The script is called:", script
print "Your first variable is:", firstargument
To run that I would pass arguments as such :
$ python test.py firstargument
Which would output
The script is called:test.py
Your first variable is:firstargument
An example input could be "Hello world the program runs" and I want to pass this as a command line argument to be stored in the 'first' variable.

argv will be a list of all the arguments that the shell parses.
So if I make
#script.py
from sys import argv
print argv
$python script.py hello, how are you
['script.py','hello','how','are','you]
the name of the script is always the first element in the list. If we don't use quotes, each word will also become an element of the list.
print argv[1]
print argv[2]
$python script.py hello how are you
hello
how
But if we use quotes,
$python script.py "hello, how are you"
['script.py','hello, how are you']
The all words are now one item in the list. So do something like this
print "The script is called:", argv[0] #slicing our list for the first item
print "Your first variable is:", argv[1]
Or if you don't want to use quotes for some reason:
print "The script is called:", argv[0] #slicing our list for the first item
print "Your first variable is:", " ".join(argv[1:]) #slicing the remaining part of our list and joining it as a string.
$python script.py hello, how are you
$The script is called: script.py
$Your first variable is: hello, how are you

Multi word command line arguments, that is single value arguments that contain multiple ASCII sequences separated by the space character %20 have to be enclosed with quotes on the command line.
$ python test.py "f i r s t a r g u m e n t"
The script is called:test.py
Your first variable is:f i r s t a r g u m e n t
This is actually not related to Python at all, but to the way your shell parses the command line arguments.

Related

How end="" with the string print statement print in same line

Everyone all of you. I am learning python right now.
In python, As you know that when we print anything using print() function it prints line by line like this:
print("Hello ")
print("World!")
When we do this then output would be:
Hello
World!
but if we want to be in same line we add end="" like this:
print("Hello ", end="")
print("World!")
Its output:
Hello World!
But I have curiosity that how does it exactly works. Why it comes in same line. The work of end="____" is to add some texts after sentences or words.
Please explain me why it comes in same line and what is the reason.
Thanks in advance!
'end' tells the print function what to end your text with. Think of it as appending that string. 'end' defaults as '\n' meaning that a new line is appended to your string by default. So, if you change it to "", you are telling it not to alter or append to your string. Which means you simply print "Hello " instead of "Hello \n"
print ("Hello, Python")
The preceeding line will print to the console "Hello, Python\n" '\n' is a new line and it is the default behavior for the print function. It will by default always add '\n' to your string. If you supply 'end' to the function, it will print that instead of '\n'.
For example, the following two lines are identical in behavior:
print ("Hello, Python")
print ("Hello, Python",end="\n")
You could however provide your own 'end' to append a different string, if you so chose. For example:
print ("Hello, Python",end="!")
The preceeding line will print, "Hello, Python!"
For more information regarding new lines, check out the following:
https://wtmatter.com/python-new-line/
It is because In python when you print statement there is end="\n" as default in the python which allow it to print in another line but you will not see it. When you put end="" then it will replace with \n which print in different line and then it prints in same line. Hope it will help

Parameters, Unpacking and variables - Learn python the hard way ex 13

I'm stuck at this point. here is the code:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "The first variable is:", first
print "The second variable is:", second
print "The third variable is:", third
my problem is this, when I run it I get:
value error need more than one value to unpack
as far as I can see I have three values and the code is good, could someone explain where I am going wrong please.
So, in chat #Ricky troubleshooted his way to successfully determining that argv was splitting on whitespace and not , comma. Changing his command line params from
$python myprog.py one,two,three
to
$python myprog.py one two three
made everything fine.
For those who wish to learn the mysteries of the argparse.

Does 'argv' in python always use script name as the first argument?

Does 'argv' in python always use script name as the first argument? How can it be avoided?
For example, I'll call this sample.py:
from sys import argv
one, two, three = argv
print "My first number is ", one
print "My second number is ", two
print "My third number is ", three
When entered into the terminal
python sample.py one two three
It returns:
ValueError: too many values to unpack
And when entered into terminal:
python sample.py one two
It returns:
python seq1.py ONE TWO
My first number is seq1.py
My second number is ONE
My third number is TWO
When running in the terminal, can you avoid the first variable always being assigned to script name?
Is there a way to have input and use just the variables you want without the script name? Or even, in some way, "mute" the printing of a throw away line with the script name?
you can do
argv[1:]
to have a list of arguments without the filename.
What this does is slicing the argv list and returning a new one without the first element. You can read more about list slicing here
Here's an example
from sys import argv
one, two, three = argv[1:]
print "My first number is ", one
print "My second number is ", two
print "My third number is ", three

python subprocess and empty strings

I am trying to use the .subprocess.check_output() function to issue commands to a crypto-coin wallet (like bitcoin, but not). Some of the commands work great, but one does not return the correct results. I suspect the use of an empty string ("") is the problem, but need help finding a solution.
I am using Python 2.7 on a Raspberry Pi B+.
My code is:
import subprocess
command = 'rimbitd getaddressesbyaccount ""'
print "The command is: ", command
results = subprocess.check_output(command.split())
print "The Results are: ", results
My output is:
pi#Pi ~ $ python Demo2.py
The command is: rimbitd getaddressesbyaccount ""
The Results are: [
]
Obviously the results are an empty set of brackets. But, if I use the exact same command directly (at the $ prompt) by copying/pasting the rimbitd getaddressesbyaccount "" from the output (i.e. "The command is: ...") then I get the following (correct) output:
pi#Pi ~ $ rimbitd getaddressesbyaccount ""
[
"RPSXNdNu4TsfyrytMSFz5RvxeSqrRyQMg6",
"RGyFKcrYR6NGr82Gqsjamj9DgEj7ZBUyfM",
"RLwQ9XGPesV35KK84oUupUh62tNori9Ahe",
"RQ2HRzX3U9NGP14dLAM7TPagNPhYKbTaVM",
"RNvR2vvaWmUnij88tTiGTXFLgZU1daKVvz"
]
pi#Pi ~ $
Other commands work as described (sending coins, checking the balance, etc.). I just can't get this one to work and the only difference is that the non-working command needs to send an empty string. I have tried using n = "" and then concatenating: commands + n (no joy). I have tried using:
results = subprocess.check_output("rimbitd", "getaddressesbyaccount", " \"\"").
I have tried using a number of methods to get the empty string through, but none have worked.
Splitting 'rimbitd getaddressesbyaccount ""' doesn't give you an empty third parameter; it gives you a parameter consisting of two quotes:
>>> 'rimbitd getaddressesbyaccount ""'.split()
['rimbitd', 'getaddressesbyaccount', '""']
You want to use
['rimbitd', 'getaddressesbyaccount', '']
for this if the last parameter needs to be empty (for which you would use a pair of double quotes when invoked from the shell prompt).
As J.F.Sebastian indicated, you can also use the shlex module:
>>> import shlex
>>> shlex.split('rimbitd getaddressesbyaccount ""')
['rimbitd', 'getaddressesbyaccount', '']
subprocess.check_output() by default doesn't run the commands in a shell. You could also have used your original .split() and provide check_output() with the shell=True keyword argument.

Python: avoid new line with print command [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 9 years ago.
When I use the print command, it prints whatever I want and then goes to a different line. For example:
print "this should be"; print "on the same line"
Should return:
this should be on the same line
but instead returns:
this should be
on the same line
More precisely I was trying to create a program with if that told me whether a number was a 2 or not
def test2(x):
if x == 2:
print "Yeah bro, that's tottaly a two"
else:
print "Nope, that is not a two. That is a (x)"
But it doesn't recognise the last (x) as the value entered, and rather prints exactly: "(x)" (the letter with the brackets). To make it work I have to write:
print "Nope, that is not a two. That is a"; print (x)
And if e.g. I enter test2(3) that gives:
Nope, that is not a two, that is a
3
So either I need to make Python recognise my (x) inside a print line as the number; or to print two separate things but on the same line.
IMPORTANT NOTE: I am using version 2.5.4
Another note: If I put print "Thing" , print "Thing2" it says "Syntax error" on the 2nd print.
In Python 3.x, you can use the end argument to the print() function to prevent a newline character from being printed:
print("Nope, that is not a two. That is a", end="")
In Python 2.x, you can use a trailing comma:
print "this should be",
print "on the same line"
You don't need this to simply print a variable, though:
print "Nope, that is not a two. That is a", x
Note that the trailing comma still results in a space being printed at the end of the line, i.e. it's equivalent to using end=" " in Python 3. To suppress the space character as well, you can either use
from __future__ import print_function
to get access to the Python 3 print function or use sys.stdout.write().
In Python 2.x just put a , at the end of your print statement. If you want to avoid the blank space that print puts between items, use sys.stdout.write.
import sys
sys.stdout.write('hi there')
sys.stdout.write('Bob here.')
yields:
hi thereBob here.
Note that there is no newline or blank space between the two strings.
In Python 3.x, with its print() function, you can just say
print('this is a string', end="")
print(' and this is on the same line')
and get:
this is a string and this is on the same line
There is also a parameter called sep that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep)
E.g.,
Python 2.x
print 'hi', 'there'
gives
hi there
Python 3.x
print('hi', 'there', sep='')
gives
hithere
If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try
from __future__ import print_function
print("abcd", end='')
print("efg")
results in
abcdefg
For those using 3.x, this is already built-in.
You simply need to do:
print 'lakjdfljsdf', # trailing comma
However in:
print 'lkajdlfjasd', 'ljkadfljasf'
There is implicit whitespace (ie ' ').
You also have the option of:
import sys
sys.stdout.write('some data here without a new line')
Utilize a trailing comma to prevent a new line from being presented:
print "this should be"; print "on the same line"
Should be:
print "this should be", "on the same line"
In addition, you can just attach the variable being passed to the end of the desired string by:
print "Nope, that is not a two. That is a", x
You can also use:
print "Nope, that is not a two. That is a %d" % x #assuming x is always an int
You can access additional documentation regarding string formatting utilizing the % operator (modulo).

Categories