![]() ![]() ![]() Spawns a (non-blocking) subprocess: We don't need to wait for the child process, since we're by problem statement starting a separate process.Error handling: It doesn't actually give us any more error detection, we're still depending on the retcode in either case but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error).In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type 'filename rm -rf /'" problem, and if the file name can be corrupted, using subprocess.call gives us little additional protection. Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other in either environment, we need the environment and services to interpret, get paths, and so forth.Now, what are the advantages of using subprocess? Print >sys.stderr, "Execution failed:", e Print >sys.stderr, "Child returned", retcode If retcode >sys.stderr, "Child was terminated by signal", -retcode Retcode = subprocess.call("open " filename, shell=True) If you need to be compatible all the way back to Python 2.4, you can use subprocess.call() and implement your own error checking: try: In Python 3.5 you can equivalently use the slightly more complex but also somewhat more versatile n(, check=True) You can also call them via subprocess module, but.įor Python 2.7 and newer, simply use subprocess.check_call() Windows: os.system("start " filename) where properly speaking filename should be escaped, too.MacOS/X: os.system("open " shlex.quote(filename)).Maybe see also python, windows : parsing command lines with shlex There is shlex.quote for Unix-like systems, but nothing really standard for Windows. A:\abc\def\a.txt), or else these need to be escaped. ![]() You can call them via os.system, which works, but.Įscaping: os.system only works with filenames that don't have any spaces or other shell metacharacters in the pathname (e.g. Here are considerations on which package to use: To call them from Python, you can either use subprocess module or os.system(). Open and start are command-interpreter things for Mac OS/X and Windows respectively, to do this.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |