Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.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
shell脚本Python中的输出值错误_Python_Shell - Fatal编程技术网

shell脚本Python中的输出值错误

shell脚本Python中的输出值错误,python,shell,Python,Shell,我有一个Python程序,其中我使用了一个返回输出值的shell脚本。下面是我的代码: #!/usr/bin/env python3 import subprocess import os import sys filename=input("Enter the filename:") val=subprocess.check_output(['bash','./grep.sh',filename]) print(val) grep.sh代码: file=$1 grep

我有一个Python程序,其中我使用了一个返回输出值的shell脚本。下面是我的代码:

#!/usr/bin/env python3
import subprocess
import os
import sys

filename=input("Enter the filename:")
val=subprocess.check_output(['bash','./grep.sh',filename])
print(val)
grep.sh代码:

file=$1
grep -c "^[0-9]" $file
我的输出:

Enter the filename:lg.txt
b'4\n'
如您所见,它将结果打印为
b'4\n'
,而不是仅打印值
4


我的代码有什么问题?如何更正此错误?

代码中没有错误

  • b
    前缀表示字节,用于从终端获取严格值
  • \n
    只是因为这是th终端返回的内容,这是末尾的新行
无论命令是什么,在检索frmo命令时都必须执行此操作

val = subprocess.check_output(['bash','./grep.sh',filename])
result = val.decode('utf-8').rstrip() # decode in UTF-8 then remove newline char