Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么sys.argv()给我的索引超出了范围?_Python - Fatal编程技术网

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

Python 为什么sys.argv()给我的索引超出了范围?,python,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 myf

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

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]
我收到一个错误,上面写着:
以open(sys.argv[1])作为myfile Indexer错误:列表索引超出范围

我正在打电话从php接收此文件:

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

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

Python代码的第一个示例(方式1)没有问题

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

python testthis.py 2>&1
Python向其引发的
索引器错误:列表索引超出范围
,因为它缺少参数

要修复在PHP中调用
exec()
时对命令的使用:

$file = 'test.txt';
exec("python testthis.py $file 2>&1", $output);
现在,
$file
可以根据需要扩展为字符串

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



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

那样返回0,如果
sys.argv[1]
抛出一个
索引器,则它没有第二个元素。你试过看它包含什么吗?听起来好像
$file
正在扩展为一个空字符串,所以你在调用Python程序时没有参数。