python as a “batch” script (i.e. run commands from python)

后端 未结 4 1258
花落未央
花落未央 2020-12-30 08:50

I\'m working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file.

how can I run a com

相关标签:
4条回答
  • 2020-12-30 08:57

    You should create a new processess using the subprocess module.

    I'm not fluent in windows processes but its Popen function is cross-platform, and should be preffered to OS specific solutions.

    EDIT: I maintain that you should prefer the Subprocess module to os.* OS specific functions, it is cross-platform and more pythonic (just google it). You can wait for the result easily, and cleanly:

    import os
    import subprocess
    unison = os.path.join(os.path.curdir, "unison")
    p = subprocess.Popen(unison)
    p.wait()
    
    0 讨论(0)
  • 2020-12-30 09:04
    import subprocess
    
    proc = subprocess.Popen(['unison', 'profile'], stderr=subprocess.PIPE,      
                            stdout=subprocess.PIPE, stdin=subprocess.PIPE)
    
    proc.stdin.write('user input')
    print proc.stdout.read()
    

    This should help you get started. Please edit your question with more information if you want a more detailed answer!

    0 讨论(0)
  • 2020-12-30 09:13

    os.execlp should work. This will search your path for the command. Don't give it any args if they're not necessary:

    >>> import os
    >>> os.execlp("cmd")
    
    D:\Documents and Settings\Claudiu>Microsoft Windows XP [Version 5.1.2600]
    (C) Copyright 1985-2001 Microsoft Corp.
    
    D:\Documents and Settings\Claudiu>
    
    0 讨论(0)
  • 2020-12-30 09:15

    I found out that os.system does what I want,

    Thanks for all that tried to help.

    os.system("dir")
    

    runs the command just as if it was run from a batch file

    0 讨论(0)
提交回复
热议问题