【问题标题】:sh: 1: Syntax error: redirection unexpected Python/Bashsh: 1: 语法错误:重定向意外 Python/Bash
【发布时间】:2016-11-05 00:44:23
【问题描述】:

我的 python cmd 脚本有问题。 我不知道为什么它不起作用。也许我的代码有问题。 我试图通过我的 python 脚本在 cmdline 中运行程序。

我在 bash "sh: 1: Syntax error: redirection unexpected" 中遇到错误

请帮助我只是生物学家:)

我正在使用 spyder (anaconda)/Ubuntu

#!/usr/bin/python

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))
    print("------------------------------------------")

【问题讨论】:

    标签: python bash shell bioinformatics


    【解决方案1】:

    output_file 是一个文件对象。当您执行"%s" % output_file 时,生成的字符串类似于"<open file 'filename', mode 'a+' at 0x7f1234567890>"。这意味着 os.system 调用正在运行类似的命令

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

    &gt;&gt; 后面的&lt; 会导致“语法错误:意外重定向”错误消息。

    要解决这个问题,不要在 Python 脚本中打开输出文件,只需使用文件名:

    output_file = sys.argv[2]
    

    【讨论】:

      【解决方案2】:

      我在以下行遇到了类似的错误:

      os.system('logger Status changed on %s' %s repr(datetime.now())
      

      确实,正如 nomadictype 所说,问题在于运行普通的操作系统命令。该命令可能包含特殊字符。就我而言,这是&lt;

      因此,我没有显着更改操作系统命令,而是添加了引号,这样就可以了:

      os.system('logger "Status changed on %s"' %s repr(datetime.now())
      

      引号使传递参数的内容对 shell 不可见。

      【讨论】:

        猜你喜欢
        • 2016-05-30
        • 2020-11-23
        • 1970-01-01
        • 1970-01-01
        • 2017-02-11
        • 2019-04-28
        • 1970-01-01
        • 2013-12-09
        • 2019-12-22
        相关资源
        最近更新 更多