如何从 Python 脚本调用 in2csv?

How can I call in2csv from a Python script?

当我尝试调用以下代码时,我 运行 出现以下错误:"You must specify a format when providing data via STDIN (pipe)."

subprocess.call(["in2csv", "--format", "xls", a_file, ">", output_file], shell=True)

我不确定为什么会这样,因为我告诉它初始格式是什么。我看过 docs,它不清楚 --format 和 -f 之间的区别。

更新: 我已将其更改为使用 argparse 来简化在 this recommendation. I'm also using Popen as used here, which is apparently safer than using shell=true flag according to the docs.

之后传递参数
parser = argparse.ArgumentParser()
parser.add_argument('in2csv')
parser.add_argument('--format')
parser.add_argument('xls')
parser.add_argument(a_file)
parser.add_argument(">")
parser.add_argument(output_file)
args = parser.parse_args()
print args
subprocess.Popen(args)

如您所见的错误是 shell 被传入的字符串混淆的症状,例如由于文件名中的 space。从 Python.

生成进程时,确实最好避免使用 shell

不要添加“>”和 output_file 作为参数,而是尝试使用 stdout 关键字参数重定向输出,这需要一个输出将被写入的文件。

假设:

  • a_file 是输入文件名的字符串,
  • output_file 是一个字符串,其中包含您想要的输出文件的名称,

工作调用可能如下所示:

with open(output_file, 'wb') as of:
  subprocess.check_call(["in2csv", "--format", "xls", a_file],
                         stdout=of)

这里没有必要使用argparse;它用于处理进入程序的命令行,而不是离开程序的命令行。