Results 1 to 4 of 4
I have a bash script that I want to import in to Python, mainly just to see if I can or not. However in the script I do use some ...
- 12-16-2010 #1Just Joined!
- Join Date
- Dec 2010
- Posts
- 10
Piping in bash using python
I have a bash script that I want to import in to Python, mainly just to see if I can or not. However in the script I do use some piping of commands into sed to trim it down to what I need. When I tried doing it with the os.system() call, it didn't work. The exact error is
However the command that was run can be run in bash without an error. Is there a better/another way to do this?sed: -e expression #1, char 16: unterminated `s' command
For reference the command is:
Code:locate -n 1 wp-config.php | sed 's/wp-config.php/\n/g' | sed '/wp-config.php/ d' | sed '/^$/ d'
- 12-17-2010 #2
I think the issue here is that you have multiple quoting rules interacting. Like probably the invocation looks something like this:
The problem is, having the whole command inside double quotes means that the usual rules for Python strings apply. For instance, try running this in Python:Code:os.system("locate -n 1 wp-config.php | sed 's/wp-config.php/\n/g' | sed '/wp-config.php/ d' | sed '/^$/ d'")
Python interprets that string as 'a-newline-b'. So there's an actual newline character (instead of a bacslash-n) in your first sed command. sed doesn't like this, it sees the newline as a statement delimiter.Code:print "a\nb"
To get around this you can use r-quoting in python:
The r"..." syntax turns off most of the usual special character syntax of the quoted string, so when you enter something like r"\n" the resulting string contains a backslash followed by 'n'.Code:os.system(r"locate -n 1 wp-config.php | sed 's/wp-config.php/\n/g' | sed '/wp-config.php/ d' | sed '/^$/ d'")
- 12-17-2010 #3Just Joined!
- Join Date
- Dec 2010
- Posts
- 10
Thank you! I completely forgot about that (it's been a while since I used python). I never knew about the r option either with print. Thanks again!
- 12-17-2010 #4
Well, it's not actually an option of print - it's an alternate syntax for string literals. If you use regular single or double quotes, you get a string that interprets backslash as part of a special character. String literals can have one or more prefix characters before the first quote: 'r' for raw strings, 'u' for Unicode.


Reply With Quote
