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

后端 未结 4 1896
梦如初夏
梦如初夏 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:18
    pat = "d:\info2.txt"
    

    In Python and most other programming languages, \ is an escape character, which is not included in a string unless doubled. Either use a raw string or escape the escape character:

    pat = "d:\\info2.txt"
    
    0 讨论(0)
  • 2020-12-03 04:23

    Escape the \ with \\:

    pat = "d:\\info2.txt"
    

    or use "raw" strings:

    pat = r"d:\info2.txt"
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 04:43

    The 'type' command doesn't run because it's an internal command - internal to the command interpreter/shell called CMD.EXE. You have to call "cmd.exe type filename" instead. The exact code is:

    call(['cmd','/C type abc.txt'])
    
    0 讨论(0)
提交回复
热议问题