Problems using subprocess.call() in Python 2.7.2 on Windows

后端 未结 4 1907
梦如初夏
梦如初夏 2020-12-03 04:16

I\'m trying the following and its failing with an error. I\'ve tried to run it from Python shell/from a script/ on the windows console by invoking python on console. Nothing

4条回答
  •  眼角桃花
    2020-12-03 04:33

    Add shell=True to call:

    >>> import subprocess
    >>> subprocess.call('dir', shell=True)
    0
    

    As you see, it gives as value the return code, not the output of dir. Also, it waits till the command completes, so doing

    >>> subprocess.call('date', shell=True)
    

    will wait for you to enter a new date.

    edit: If you want to capture the output, use subprocess.check_output. The DOS command type for example prints out the contents of a file. So, suppose that your file info2.txt contains your username, you would do:

    >>> import subprocess
    >>> path = r'd:\info2.txt'
    >>> output = subprocess.check_output(['type', path], shell=True)
    >>> print output
    Vinu
    

    For all the ways to call external commands in Python, see this comprehensive overview to a related question, for more about subprocess specifically, see this article by Doug Hellmann.

提交回复
热议问题