简体   繁体   中英

Python 3: Using subprocess Instead Of os.system

I have a string called variable and need to do the subprocess equivalent of 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 .

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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