Python subprocess.Popen() error (No such file or directory)

前端 未结 2 2050
误落风尘
误落风尘 2020-12-11 00:28

I am trying to count the number of lines in a file using Python functions. Within the current directory, while os.system(\"ls\") finds the file, the command

相关标签:
2条回答
  • 2020-12-11 00:59

    You should pass the arguments as a list (recommended):

    subprocess.Popen(["wc", "-l", "sorted_list.dat"], stdout=subprocess.PIPE)
    

    Otherwise, you need to pass shell=True if you want to use the whole "wc -l sorted_list.dat" string as a command (not recommended, can be a security hazard).

    subprocess.Popen("wc -l sorted_list.dat", shell=True, stdout=subprocess.PIPE)
    

    Read more about shell=True security issues here.

    0 讨论(0)
  • 2020-12-11 01:03

    The error occurs because you are trying to run a command named wc -l sorted_list.dat, that is, it is trying to find a file named like "/usr/bin/wc -l sorted dat".

    Split your arguments:

    ["wc", "-l", "sorted_list.dat"]
    
    0 讨论(0)
提交回复
热议问题