Marcin Gradowski Marcin Gradowski - 9 months ago 131
Bash Question

sh: 1: Syntax error: redirection unexpected Python/Bash

I have problem with my python cmd script.
I don't know why it does not work. Maybe something wrong with my code.
Im trying to run the program in cmdline through my python script.

And Im getting error in bash "sh: 1: Syntax error: redirection unexpected"

pls help Im just biologist :)

Im using spyder (anaconda)/Ubuntu


import sys
import os

input_ = sys.argv[1]
output_file = open(sys.argv[2],'a+')
names = input_.rsplit('.')

for name in names:
os.system("esearch -db pubmed -query %s | efetch -format xml | xtract -pattern PubmedArticle -element AbstractText >> %s" % (name, output_file))

Answer Source

output_file is a file object. When you do "%s" % output_file, the resulting string is something like "<open file 'filename', mode 'a+' at 0x7f1234567890>". This means that the os.system call is running a command like

command... >> <open file 'filename', mode 'a+' at 0x7f1234567890>

The < after the >> causes the "Syntax error: redirection unexpected" error message.

To fix that, don't open the output file in your Python script, just use the filename:

output_file = sys.argv[2]