如何通过python执行shell脚本
我有一个脚本说abc.sh其中有带有标志的命令列表。 示例如何通过python执行shell脚本
//abc.sh
echo $FLAG_name
cp $FLAG_file1 $FLAG_file2
echo 'file copied'
我想通过python代码执行此脚本。 说
//xyz.py
name = 'FUnCOder'
filename1 = 'aaa.txt'
filename2 = 'bbb.txt'
subprocess.call([abc.sh, name, filename1, filname2], stdout=PIPE, stderr=PIPE, shell=True)
此调用不起作用。
还有什么其他的选择?
此外,shell脚本文件位于其他目录中。我希望输出进入日志。
通常您希望使用Popen
,因为您之后有过程控制。尝试:
process = subprocess.Popen(['abc.sh', name, filename1, filname2], stdout=PIPE, stderr=PIPE)
process.wait() # Wait for process to complete.
# iterate on the stdout line by line
for line in process.stdout.readlines():
print(line)
试试这个:
//xyz.py
name = 'FUnCOder'
filename1 = 'aaa.txt'
filename2 = 'bbb.txt'
process = subprocess.Popen(['abc.sh', name, filename1, filname2], stdout=PIPE)
process.wait()
注意,“abc.sh”是加引号,因为它不是一个变量的名字,但你调用命令。
我一般也会推荐使用shell=False
,虽然在某些情况下有必要使用shell=True
。
要使输出到文件尝试:
with open("logfile.log") as file:
file.writelines(process.stdout)
我跑这个......但没有输出....是输出重定向在这里好吗? – 2013-04-23 23:19:46
尝试在没有管道的情况下运行它 – 2013-04-23 23:20:31
我打印了此调用的retcode并且它说0 ...这意味着它的失败...任何想法为什么? – 2013-04-23 23:22:41
有你使用[shutls(http://docs.python.org/2/library/shutil.html),而不是一个bash脚本考虑。试试'shutils.copyfile' – 2013-04-23 23:17:50
这里使用'shell = True'是错误的并且会引发错误。 – 2013-04-24 15:27:00