简体   繁体   English

Python 3:使用子进程代替os.system

[英]Python 3: Using subprocess Instead Of os.system

I have a string called variable and need to do the subprocess equivalent of os.system . 我有一个名为variable的字符串,需要执行os.systemsubprocess os.system等效os.system I've tried to find a way to do this but have only found: 我试图找到一种方法来做到这一点,但只发现了:

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

However, I'm having trouble understanding how to use it. 但是,我在理解如何使用它时遇到了麻烦。 How do I achieve my goal? 我如何实现目标?

The documentation provides equivalents for several old-style sub-process creation functions. 该文档提供了几种旧式子流程创建功能的等效项。 os.system() is explained here . os.system() 在这里解释。

In [4]: os.system('uname -a')
Linux diego-workstation 3.0.0-16-generic #28-Ubuntu SMP Fri Jan 27 17:44:39 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
Out[4]: 0

In [8]: subprocess.call(['uname', '-a'])
Linux diego-workstation 3.0.0-16-generic #28-Ubuntu SMP Fri Jan 27 17:44:39 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
Out[8]: 0

Look at the subprocess.call , subprocess.check_call and subprocess.check_output functions. 查看subprocess.callsubprocess.check_callsubprocess.check_output函数。 You may need to pass shell=True if you are executing a shell command (as would be given to os.system) rather than explicitly specifying the executable and a sequence of arguments. 如果要执行shell命令(如os.system所给),则可能需要传递shell=True ,而不是显式指定可执行文件和参数序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM