如何在 Python 脚本中执行 UNIX 命令 [英] How to execute a UNIX command in Python script
问题描述
#!/usr/bin/python
import os
import shutil
import commands
import time
import copy
name = 'test'
echo name
我有一个像上面这样的简单 python 脚本.当我尝试执行它时,在尝试输出 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.
推荐答案
您不能在 Python 脚本中使用 UNIX 命令,就像它们是 Python 代码一样,echo name
导致语法错误,因为 echo
不是 Python 中的内置语句或函数.相反,使用打印名称
.
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
.
要运行 UNIX 命令,您需要创建一个运行该命令的子进程.最简单的方法是使用 os.system()
,但最好使用 subprocess
模块.
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.
这篇关于如何在 Python 脚本中执行 UNIX 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!