为什么sys.argv()给我一个超出范围的索引?

时间:2016-02-20 10:53:26

标签: python

我的纺织品内容如下:

honda motor co of japan doesn't expect output at its car manufacturing plant in thailand

当我运行wc -l textfile.txt时,我收到0。

问题是我正在运行一个python脚本,需要计算此文本文件中的行数并相应地运行。我已经尝试了两种计算行数的方法,但它们都给我0并且我的代码拒绝运行。

Python代码:

#Way 1
with open(sys.argv[1]) as myfile:
    row=sum(1 for line in myfile)
print(row)

#Way 2
row = run("cat %s | wc -l" % sys.argv[1]).split()[0]

我收到一条错误消息:with open(sys.argv[1]) as myfile IndexError: list index out of range

我正在调用从php接收此文件:

exec('python testthis.py $file 2>&1', $output);

我怀疑argv.sys [1]给我一个错误。

1 个答案:

答案 0 :(得分:2)

Python代码的第一个示例(方法1)没有任何问题。

问题是PHP调用代码;传递给exec()的字符串使用single quotes,这可以防止$file变量扩展到命令字符串中。因此,生成的调用将文本字符串$file作为参数传递给exec(),后者又在shell中运行命令。该shell将$file视为shell变量并尝试展开它,但它未定义,因此它扩展为空字符串。结果是:

python testthis.py 2>&1

Python引发IndexError: list index out of range,因为它缺少一个参数。

在PHP中调用exec()时修复命令周围的使用double quotes

$file = 'test.txt';
exec("python testthis.py $file 2>&1", $output);

现在可以根据需要将$file扩展为字符串。

这确实假设您确实想要将PHP变量扩展为字符串。因为exec()在shell中运行命令,所以也可以在shell的环境中定义变量,并且shell将它扩展为最终命令。为此,使用传递给exec()的命令的单引号。

请注意,“方式1”的Python代码将返回行数1,而不是wc -l

相关问题