Python: Command line arguments not read? - python

I'm trying to read command line arguments in python in the form:
python myprogram.py string string string
I have tried using sys.argv[1-3] to get each string, but when I have a string such as $unny-Day, it does not process the entire string. How can I process strings like these entirely?

Are you using a shell? $ is a special character in the shell that is interpreted as a shell variable. Since the variable does not exist, it is textually substituted with an empty string.
Try using single quotes around your parameter, like > python myapp.py '$unny-Day'.

Related

Provide quotes as input command line in python [duplicate]

This question already has answers here:
How to escape single quotes within single quoted strings
(25 answers)
When to wrap quotes around a shell variable?
(5 answers)
Closed last year.
I'm trying to process an input string in a Python script which is taken as a command line argument. This input might contain quotes as well (both single and double is possible) and I'm not able to provide it as input. I tried escaping it (with \), does not work.
Here are the details:
python3 code.py --foo="foo" //works
python3 code.py --foo='foo' //works
python3 code.py --foo='f"o"o' //works
python3 code.py --foo="fo'o'" //works
python3 code.py --foo="fo\"o" //does not work
python3 code.py --foo='fo\'o' //does not work
For my use case, there could also be a mixture of single or double quotes as well. Is there a workaround?
If it matters, here is the relevant code:
import argparse
parser = argparse.ArgumentParser(description="Demo")
parser.add_argument("--foo", required=True)
args = parser.parse_args()
print(args.foo)
Here is what happens when I try and run using input that "does not work":
$ python3 code.py --foo='v\'1'
> ^C
I get a "prompt", which I then exit by ctrl-C. Basically, \ does not escape the (middle) quote, and bash identifies my command as incomplete.
In a unix shell, to easily figure out the exact string you need to send to any commandline argument, you can use Python's shlex.quote():
>>> import shlex
>>> arg = r'''"fo\"o"'''
>>> print(shlex.quote(arg))
'"fo\"o"'
Make sure you wrap the argument with r and triple quotes.
If you happen to have triple quotes in your string, you'll have to manually escape everything without using r.

How to display \r\n as actual new line in command prompt?

I have this Python code which goes like
output = str(check_output(["./listdevs.exe", "-p"]))
print (output)
When running this Python code in the Command Prompt, I'm met with this output
b'80ee:0021\r\n8086:1e31\r\n'
Instead of the above output, I would like to display it where the \r
\n is replaced with an actual new line where it would look like
'80ee:0021
8086:1e31'
The result is in bytes. So you have to call decode method to convert the byte object to string object.
>>> print(output.decode("utf-8"))
If you are using Python 3.7+, you can pass text=True to subprocess.check_output to obtain the results as a string.
Prior to 3.7 you can use universal_newlines=True. text is just an alias for universal_newlines.
output = str(subprocess.check_output(["./listdevs.exe", "-p"], text=True))

Preserve single and double quotes inside bash script

I have to run a python script within bash, passing it a string which is stored in a variable... so inside bash I have:
python my_script.py $myvariable
myvariable is a string that can contain single/double quotes which I would preserve (since I make some splits in python script using that quotes). How could I preserve that quotes? Can I escape them somehow before passing to python? I know that I could surround myvariable too with single/double quotes, but I don't know the content of the string, so it would be faulty.

Python3 doesnt detect tuple

I have this input:
python script.py --key '("music","aaa")' --date '("01/01/1990",0,0)'
And I do:
constrain = literal_eval(sys.argv[2])
print(type(constrain))
print(type(sys.argv[4]))
And all outputs are str while they should be tuples. The input cannot be changed!
You're command line should work perfectly from MSYS or Linux, but here you're running it from windows shell.
Windows shell doesn't treat simple quotes as syntatcic. They're passed literally to your python code. To top it all, the double quotes are removed which makes your second arg '(music,aaa)' when passed to python: no way you can literal_eval that. So your input string has to be changed (or your operating system :))
Do this to call your code:
python script.py --key "(""music"",""aaa"")" --date "(""01/01/1990"",0,0)"
You have to quote the arguments and double the quotes in the arguments. And use double quotes exclusively.
EDIT: or even better (would work on both Linux and Windows): use simple quotes inside your arguments, double quotes outside (literal_eval is not json: it understands both simple & double quotes!):
python script.py --key "('music','aaa')" --date "('01/01/1990',0,0)"
now I'm getting:
<type 'tuple'>
<type 'str'>
(you get str because the 4th argument is always a string, you probably forgot to literal_eval it)
and print(constrain) yields:
('music', 'aaa')
(so it's not a python issue, rather a CMD issue)

Condor quoting hell

I'm having trouble with passing a string representation of a dict to be read in by json.loads in Python through Condor.
On the command line I would type:
python script.py arg1 "{'x':50,'y':'a'}"
After much struggle with the docs, I understand Condor wants in the submit file:
arguments = "arg1 '""{''x'':50,''y'':''a''}""'"
However it is failing and claiming quadruple single quotes around the dict strings in the log, eg:
''''x'''':50
Is there any way to manipulate the quotes to get it to run as expected?

Categories