在 Python 中,我如何使用 subprocess 而不是 os.system? [英] In Python, how I do use subprocess instead of os.system?

查看:52
本文介绍了在 Python 中,我如何使用 subprocess 而不是 os.system?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python 脚本,它使用各种参数调用可执行程序(在本例中,它是sqlpubwiz.exe",即Microsoft SQL Server 数据库发布向导"):

I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"):

import os

sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"'
server = 'myLocalServer'
database = 'myLocalDatabase'
connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true']
connection_string = ';'.join(connection_values)
dbms_version = '2000'
sqlscript_filename = 'CreateSchema.sql'

args = [
        sqlpubwiz,
        'script',
        '-C ' + connection_string,
        sqlscript_filename,
        '-schemaonly',
        '-targetserver ' + dbms_version,
        '-f',
]

cmd = ' '.join(args)
os.system(cmd)

此代码运行正常,但我想养成使用 subprocess 的习惯因为它旨在替换 os.system.但是,经过几次失败的尝试后,我似乎无法正常工作.

This code runs properly but I have would like to get into the habit of using subprocess since it is intended to replace os.system. However, after a few failed attempts, I can not seem to get it work properly.

如果将上面的代码转换为使用 subprocess 代替 os.system 会是什么样子?

How would the above code look like if it was converted to use subprocess in place of os.system?

推荐答案

import subprocess
p=subprocess.Popen(args, stdout=subprocess.PIPE)
print p.communicate()[0]

看起来几乎一样.但是路径不应该是 r'"无论路径是什么"'.因为这给了我一个错误.您想要带有转义反斜杠的路径"或没有转义的路径".

It would look pretty much the same. But the path should not be r'"whatever the path is"'. Because that gives me an error. You want "the path with escaped backslashes" or r'the path without escaping'.

args 也应该是 ['-arg', 'args'] 的形式,而不是 ['arg argsval'].

Also args should be of the form ['-arg', 'args'] instead of ['arg argsval'].

这篇关于在 Python 中,我如何使用 subprocess 而不是 os.system?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆