【问题标题】:How to read input to python in bash如何在bash中读取python的输入
【发布时间】:2016-12-26 10:18:38
【问题描述】:

我有来自here 的代码,我想在 bash 中使用这个 python 脚本,例如:

python转换.py sample.tsv sample.xlsx

python 脚本:

import csv
from xlsxwriter.workbook import Workbook

# Add some command-line logic to read the file names.
tsv_file = 'sample.tsv'
xlsx_file = 'sample.xlsx'

# Create an XlsxWriter workbook object and add a worksheet.
workbook = Workbook(xlsx_file)
worksheet = workbook.add_worksheet()

# Create a TSV file reader.
tsv_reader = csv.reader(open(tsv_file, 'rb'), delimiter='\t')

# Read the row data from the TSV file and write it to the XLSX file.
for row, data in enumerate(tsv_reader):
    worksheet.write_row(row, 0, data)

# Close the XLSX file.
workbook.close()

如何修改这个 python 脚本。抱歉,这个问题可能很愚蠢,但我不使用 python。

【问题讨论】:

  • import sys, tsv_file = sys.argv[1], xlsx_file = sys.argv[2].

标签: python bash


【解决方案1】:

您可以使用sys.argv

....

tsv_file = sys.argv[1]

xlsx_file = sys.argv[2]

...

你可以这样运行:

main.py sample.tsv sample.xlsx

您也可以检查 argparse 包。它提供了许多花哨的功能。它基本上是 sys.argv 的包装器。

【讨论】:

  • 嗨,谢谢你的回复 - 我有这个错误:回溯(最近一次调用最后一次):文件“conversion_xlsx.py”,第 5 行,在 tsv_file = sys.argv[1] NameError:名称'sys'未定义,知道吗?非常感谢。
  • 我忘记导入系统了。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多