How to execute a UNIX command in Python script

北战南征 提交于 2020-01-23 02:43:12

问题


#!/usr/bin/python

import os
import shutil
import commands
import time
import copy

name = 'test'

echo name 

I have a simple python scripts like the above. When I attempt to execute it I get a syntax error when trying to output the name variable.


回答1:


You cannot use UNIX commands in your Python script as if they were Python code, echo name is causing a syntax error because echo is not a built-in statement or function in Python. Instead, use print name.

To run UNIX commands you will need to create a subprocess that runs the command. The simplest way to do this is using os.system(), but the subprocess module is preferable.




回答2:


you can also use subprocess module.

import subprocess
proc = subprocess.Popen(['echo', name],
                            stdin = subprocess.PIPE,
                            stdout = subprocess.PIPE,
                            stderr = subprocess.PIPE
                        )

(out, err) = proc.communicate()
print out

Read: http://www.doughellmann.com/PyMOTW/subprocess/



来源:https://stackoverflow.com/questions/10905427/how-to-execute-a-unix-command-in-python-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!