Python Search String One Liner - python-2.7

I'm trying to use Python a little more and I know this isn't the best use case for it but it's bothering me on why I can't get it to work.
I'm currently using Python 2.7.6 and I want to cat a file and then pull specific strings out of it based on regex. The below code works fine for what I want, but only looks at the first line.
cat /tmp/blah.txt | python -c "import re,sys; m = re.search('Host: (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*OS:(.*) Seq:', sys.stdin.read()); print m.group(1), m.group(2)"
So I assumed I could just use a for loop or fileinput to read the entire file and then put the rest of my code in there but I keep on getting errors with the for loop.
cat /tmp/blah.txt | python -c "import sys; for line in sys.stdin: print line" File "<string>", line 1
import sys; for line in sys.stdin: print line
^
SyntaxError: invalid syntax
I've tried a few variations of this but can't get it to work. It always says invalid syntax at the for portion. I know it has to be something very stupid/obvious I'm doing but any help would be appreciated.
If I created a program called arg.py and put the code below in it and call Python via cat, it works fine. It's just the one liner portion that isn't working.
import sys
for line in sys.stdin:
print line

Unfortunately, constructs that introduce indentation in python like if, for among others are not allowed to be preceded by other statements.
Even in your arg.py file try the following:
import sys; for line in sys.stdin: print line
You will discover that the syntax is also invalid which results to the same error.
So, to answer your question, your problem is not the fact that you ran the program in the terminal but the problem is in python syntax itself. It does not support such syntax
Check out a related question

Related

Python 2.7.15 adds a new line in Windows to the end but not on Linux. How do I fix this?

This is not a typical "how do I strip a new line or spaces" question...
I am new to python in general. But I am aware of
print ("test", end="")
print ("test", end="")
for Python 3 and
print "test",
print "test",
for Python 2
Python 3 implementation will print correctly on both Linux and Windows machines; however the Python 2 implementation will add an extra line at the end of the execution on Windows based machines (but not Linux, there it prints correctly). Is there any way to get rid of this new line?
I have searched around and I cant seem to find anyone talking about this particular issue. Here is a screenshot for demonstration:
So, in accordance with the print documentation
Standard output is defined as the file object named stdout
And we probably assume that python I\O are system dependent, so that's how we could try to guess the explanation of this situation, even thought print documentation states:
A '\n' character is written at the end, unless the print statement
ends with a comma.
OR The reason is that Windows & Linux threat print statement differently (since print is a statement in Python 2, and a function call in Python 3).
Back to the question, how to get rid of this line:
I used future statement for print function:
from __future__ import print_function
print('test', end=' ')
print('test', end='')
If I find any reasonable explanation, I will update the answer (should be somewhere !).
After speaking to a few people about this and doing some research. It appears the most straightforward way around this issue is to directly use:
sys.stdout.write()
instead of print. You can then format your output similar to the way C/C++ and Java work.

How to enter command line arguments in python notepad++?

I am practicing beginner's Python in Notepad++ and I am stuck when trying to give command line arguments during runtime. When I run the code, I get ValueError: need more than 1 value to unpack, and I can't give input arguments. I tried using Python plugins PyNPP, NppExec and even tried running it through Notepad++'s inbuilt console but I'm still unable to give input. There is no syntactical error in the code:
from sys import argv
script, first, second, third = argv
print "the script is called : ", script
print "your first variable is : ", first
print "your second variable is :", second
print "your third variable is: ", third
Please explain how I can give arguments during runtime. I have searched in Google for possible solutions.
argv is a list of arguments to the python script. It should not be defined inside a script. An example:
python script.py first second third
In this case
sys.argv[0] is script.py
sys.argv[1] is first
sys.argv[2] is second
sys.argv[3] is third

Why i cant get the process that exist on print?

import os
import time
os.system('WMIC /OUTPUT:C:\Users\PRO\Desktop\ProcessList.txt PROCESS get Caption')
with open('C:\Users\PRO\Desktop\ProcessList.txt', 'r') as f:
if str('System') in f:
print "Yes"
else:
print "No"
I have tried your code, and it was needed some little modification. I did that, but didn't get desirable result. It write successfully in a mentioned file. So, I though it would be better if I print out each line in my python IDLE. I got such weird result.
At first, it looked fine, when open in any text editor. But later, after finding this weird space between each character, I opened this file in Sublime editor, run over there, then found something look like this
After googling a little bit, I found that this is a NUL terminator used to teminate the string in C\C++. Maybe someone with more knowledge about this can explain it better.
I have no idea, how and why it is adding it after every character. But if you remove that and run again the code, you'll get the desirable result.
Kindly find the below updated code:
import os
import time
os.system('WMIC /OUTPUT:C:\Users\sohan.tirpude\Documents\LogInLog.txt PROCESS get Caption')
searchfile = open("C:\Users\sohan.tirpude\Documents\LogInLog.txt", "r")
for line in searchfile:
line = line.replace('\0', '')
#print line
if 'System' in line:
print "Yes"
break
else:
print "No"
Kindly give it a try.

Biopython translate output error

I'm constructing a bash script that incorporates grep and small Python scripts ultimately capable of searching a genetic sequence file (fasta format) for strings of sequence of a given length between two sequence search strings and translating those sequences into peptides. My bash script uses two grep functions followed by a Biopython script that prints the first few lines corresponding to the desired region.
grep -E -o "ATGAGTCTT(.*)TCAGTACG" search_script_testdata.fasta > ./output1.txt
grep -E -o "(.*)TCAGTACG" output1.txt > ./output2.txt
python print_int.py > ./output3.txt
python translate.py > ./output4.txt
The code works until python translate.py.
from Bio.Seq import translate
for line in open("output3.txt"):
translate(line)
The output for translate.py is the following if run when within Python
Bio/Seq.py:1976: BiopythonWarning: Partial codon, len(sequence) not a multiple of three. Explicitly trim the sequence or add trailing N before translation. This may become an error in future.
BiopythonWarning)
'LVS'
'SLD'
The penultimate file that I hope to generate would have just the information
LVS
SLD
However, when the bash script runs, only the warning/error message and not the two amino acid sequences are output to the screen and nothing is written to output4.txt. The amino acid sequences aren't supposed to start with a Methionine, which is the source of the error message. I need the sequences in this format. Can anyone with experience in Biopython lend a hand and suggest how I can get only the amino acid sequences to output to a file?
Edit:
I've since changed the search_script_testdata.fasta file so that the expected output3.txt file would have only three lines of ATGAGTCTT which translates to MSL.
output3.txt
ATGAGTCTT
ATGAGTCTT
ATGAGTCTT
The resulting error is the same as before.
translate.py is a file with the following lines of code:
for line in open("output2.txt", "r"):
print(line[:9])
This time I get
'MSL'
'MSL'
'MSL'
with the same error message. My understanding is that this code should work with files set up such that each line has one string of genomic sequence to be translated. There is a separate method in the biopython cookbook for dealing with fasta file format translation.
Any thoughts?
If your file translate.py really looks like this:
from Bio.Seq import translate
for line in open("output3.txt"):
translate(line)
you shouldn't expect any data to be directed to the standard output and redirected to output4.txt file.
Print the translated sequence to stdout:
print translate(line)

Detecting errors of a command that print nothing if the command was successful using Perl and Expect

I am trying to automate the configuration of a server using perl and the expect module. I have been using the expect module three days but now I have encountered a problem that I can't solve.
My problem is when im executing a command that prints no output if it is successful but prints an error message if something went wrong. An example of such command is the cd command:
$ cd .
$
$ cd sadjksajdlaskd
sadjksajdlaskd: No such file or directory.
$
What I would like to do is to send the command to the server, and then perform an expect call to check if something other than the prompt sign was printed. Something like this:
$com->send("cd $dir");
$com->expect(2,
["^[^$#]*", sub {
my $self = shift;
my $error = $self->match();
die "ERROR: $error";
}],
"-re", "^[$#]"
);
The problem I have is that when I perform the expect call it will match against all previous text and not against text received after the send call, so it will always match and report an error. How do I make expect match only agains the text received after the send call? Is it possible to clear the buffer of the expect module or is it possible to achieve this kind of error detection some other way?
I also wonder how the expect module handles regular expressions. If I for example use "^[$#]\$" as the regular expression to match the prompt of the terminal, will the \$ part of the regular expression match end of line or an actual dollar sign? If i remove the \ perl complains.
Thanks in advance!
/Haso
EDIT: I have found a solution:
The solution was to use $com->clear_accum() which clears the accumelator. I have tried using it before but it seems like this function only works at random, or maybe I don't understand what clear_accum() is suppose to do.
EDIT: A final note about clear_accum():
The reason the clear_accum() function seems to work at random is because the text generated from the previous send is not read into the accumelator until an expect() call is made. So in order to truly clear all previous data is to first perform an expect() call and then clear the accumelator:
#To clear all previous data
$com->expect(0);
$com->clear_accum();
akarageo#Pal4op:~> cd banana
bash: cd: banana: No such file or directory
akarageo#Pal4op:~:( > echo $?
1
i.e. check the error code that CD returns, 0 means OK anything else is an error, No need to check the prompt , and btw, the CD command does not generate the prompt the shell does, so that must be part of your confusion also.
try $object->exitstatus() if it is of any help