Python system argument reading '&' - python

I want to pass url to my python via the console and then do the appropriate tasks. many of the links contain the character '&' in the link. python interprets that as ending the argument this however is not what I want. here is a sample of the code
import sys
external_id = sys.argv[1].encode("utf-8")
print external_id
And when I run the following:
python graph.py 2%60&7
I get:
2%60
How do I make python interpret the '&' as nothing more than another character in the url?

This is not python, it's bash. You need to escape it:
python graph.py 2%60\&7

Quoting this answer:
The & informs the shell to put the command in the background.
Python never receives that character because the shell takes care of it, thus this isn't an issue of Python. You can also wrap 2%60&7 with quotes to make it work
me#pc:~$ python3 script.py '2%60&7'
b'2%60&7'
Sometimes escaping & is a lot harder than doing this.

Related

PYTHON Script not using OS Commands

Within a UBUNTU VM, using GNS3 I created code that is an attempt to after the user's input perform one of 3 different outcomes, however, the if statements don't work, the python files can't be found which I was trying to point to this the cd/home.. command. And the curl commands are apparently the incorrect syntax even though that is what I would enter for them to work. please help me out and get this working.
This is what I tried:
#!/usr/bin/python3
import os
import subprocess
Code = input("Enter RYU, ONOS or CURL:")
print("Command entered was: " + Code)
if input == 'RYU':
os.system('rest_router.py')
os.system('gui_topology.py')
elif input == "ONOS":
os.system('sudo /opt/onos/bin/onos-service start')
You are using single quotes to quote something that already has single quotes. By doing so, what should be an opening quote in your curl command is now effectively a closing quote in your Python, and Python doesn't understand why there is now a random ( there where Python code should continue.
I underlined what is quoted in the following examples. Note that even syntax highlighting in most any editor (and also here on Stack Overflow) is helping you see what is inside a string and what is not, colouring them differently (though syntax highlighting can be fallible):
echo 'foo' bar
---
But:
os.system('echo 'foo' bar')
----- ----
To fix, you can escape the inner quotes, so Python treats them as any regular character inside the string:
os.system('echo \'foo\' bar')
----------------
Or you can change the outer quotes. Python has several sets of quotes; you can't use ' or " since you're already using both of them inside the string, but you can use ''' or """:
os.system('''echo 'foo' bar''')
--------------

"net use" didn't work in Python 3 script

I want to access some files in my network drive.
My network drive is called "networkfile". If I just run this on the Window command line, it is working: net use \networkfile\Programs.
However, It didn't work when I put it in the Python script (I'm using Python3). I tried:
a = os.system("net use O:\networkfile\Programs")
a = os.system("net use \networkfile\Programs")
a = os.system("net use \networkfile\Programs")
a = subprocess.run("net use O:\networkfile\Programs", shell=True, stdout=subprocess.PIPE)
None of those work. The error is: "System error 67 has occurred. The network name cannot be found."
Anyone has experienced this before?
Please advice.
Thanks,
your string "net use O:\networkfile\Programs" is being evaluated by the python interpreter as:
net use O:
etworkfile\Programs
because the \n is interpreted as a newline character. You can work around this in a couple different ways
use a raw string (see four paragraphs down here) to prevent backslashes being treated specially (in most cases).
escape the backslashes themselves so they evaluate to a literal backslash (make all "\" into "\\")
use the os.path library to generate the string so the correct directory separator is used regardless of operating system.

How to programmatically escape quotes andd slashes

I need a python script to call a bash script on windows.
So basically I must make a subprocess call form python, that will call cygwin with the -c option that will call the script I need,
The problem is that this script takes a few arguments and that these arguments are full os spaces and quotes and slashes.
I'm using code like the following
arq_saida_unix = arq_saida.replace("\\","/")
subprocess.call("C:\\cygwin64\\bin\\bash \".\\retirarVirgula.sh\\ \""+arq_saida+"\"")
Or I'm directly escaping, which sometimes takes me to as much as 8 backslashes in a row, for a backslash to get to my script must be escaped i) in bash ii) in cmd.exe iii) in python
all of this is error prone and takes quite some time every time to get it right.
Is there a better way of doing it? Ideally I wouldn't have any escaping backslashes, but anything that avoids the triple-slash double quote above would be nice.
I tried to use re.escape, but could figure out how exactly to use it , except as a replacement to .replace("\","/") and similar.
Don't pass a single string to call; instead, pass a list consisting of the command name and one argument per element. This saves you from needing to protect special characters from shell interpretation.
subprocess.call(["retirarVirgula.sh", arq_saida], executable=r"C:\cygwin64\bin\bash")
Note: I'm assuming arq_saida contains the single argument to pass to the script; if the script takes multiple arguments, then arc_saida should probably be built as a list as well:
arq_saida = ["arg", "arg two", "arg three"]
subprocess.call(["retirarVirgula.sh"] + arq_saida, executable=r"C:\cygwin64\bin\bash")

How do I used 2 quotes in os.system? PYTHON

I have a little bit of problem when I'm trying to use 2 quotes in os.system..
I'm gonna launch a program with python, the directory has multiple spaces, and to launch something that has multiple spaces in CMD you need to put double quotes around it obviously.
And here comes the thingy..
my code looks like this:
import os
os.system("C:/t est/hello")
and since I used os.system, it will obviously just send C:/t est/hello that to CMD..
Now what I need is to send "C:/t est/hello" to cmd with quotes but I need python to understand that I need 2 quotes aswell. Can someone please help me?
If you want to add quotes to your command, simply do so. Possibly the easiest way is to use single quotes for your string:
os.system('"C:/t est/hello"')
If you want to write a double quote inside a string delimited by double quotes you need to escape it. That would be done like this:
os.system("\"C:/t est/hello\"")
However, it's just a lot easier to use subprocess instead and let it handle quoting for you. For example:
subprocess.check_call(['ls', 'some directory with spaces in'])
Even the documentation for os.system() recommends using subprocess:
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

Program error while using python subprocess.call() function

I'm trying to open a program while I'm in a python script using the subprocess.call() function, It opens the program but for some reason the program doesn't allows that and just throw an "Unhandaled exception" error, I know the problem is probably in the program so there may be any other command that will open a program, fill some fields and press "Submit?"
Thanks!
Edit: I've no code to post..
str = 'd:\Softwares\X.exe'
subprocess.call(str)
I've also tried with:
subprocess.call(str,shell=True)
Try calling another program the same way. If the problem persists, the problem is with your code. If it goes away, the problem is with the program.
I think changing to 'D:/Softwares/X.exe' or one of the other string formats will help because the '\' character is the escape character ... used for example to denote a new line '\n'.
It probably works if you use forward-slashes (backslashes are escape symbols in Python). If it doesn't, write the first line like this:
str = r'd:\Softwares\X.exe'
The r tells Python that you are creating a raw string, so it will ignore escape symbols. More information at: https://docs.python.org/2/reference/lexical_analysis.html#string-literals

Categories