为什么是系统argv()给我一个超出范围的索引?

2024-04-25 08:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一种纺织品,内容如下:

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

当我跑厕所的时候文本文件.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] 给了我一个错误。你知道吗


Tags: of代码inoutputas错误withsys
1条回答
网友
1楼 · 发布于 2024-04-25 08:35:37

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()的命令周围使用单引号。你知道吗


注意,“way1”的Python代码将返回1的行计数,而不是像wc -l那样返回0。你知道吗

相关问题 更多 >