为UNIX命令行编写python脚本

时间:2014-04-24 01:21:34

标签: python unix

嘿,我下周有一个使用编译器的作业,教授希望我们编写一个脚本实际上是命令行。我是python的新手,在UNIX上编写脚本。 你如何在Python上编写脚本? 我需要教程或任何建议

谢谢

我们必须写下这些步骤

对于每个实验,请按以下步骤操作:

For each benchmark directory, change to that directory and compile the code with one of the optimization levels. For example:

cd adpcm
gcc -O0 -o adpcm-O0 adpcm.c

Time the runtime of the executable:

time ./adpcm-O0
Record the “real” time displayed. You might take an average of 3-5 runs to get a stable result.

Use the performance measurement tools

On the Pis:

run rpistat on the executable
e.g. rpistat ./adpcm-O0
that generates a textfile rpistat.txt in the same directory. Record the Cycles and Instructions (use the value in [brackets] for the instruction count).

On the lab workstations:

run perf on the executable
e.g. perf stat ./adpcm-O0
that prints to stdout (you can redirect if you wish). Record the Cycles and Instructions.

Repeat this procedure for all 12 benchmarks and all 4 optimization levels on both machines.
For the fastest version of each benchmark (use lowest cycle count in the case of a tie), profile the application:

gcc -pg -O2 -o adpcm-prof adpcm.c
./adpcm-prof  (This is needed to profile the executable, but you don’t need to record the runtime)
gprof ./adpcm-prof | less
Record the function for which the most execution time is spent. 

3 个答案:

答案 0 :(得分:3)

subprocess.Popen,os.listdir,os.chdir和time.time()应该有所帮助。这些都是python命令。您可以使用" import subprocess"来获取子进程模块,使用" import os"来获取os模块。

要创建Python脚本,只需在* ix上使用您喜欢的文本编辑器编辑文本文件(名为"-script"对于此示例),内容如下:

#!/usr/bin/python3
# or you can use python 2 with /usr/bin/python

print('hello world')

...并使其可执行:

chmod 755 the-script

...然后你可以像以下一样运行它:

./the-script

HTH

答案 1 :(得分:0)

要在shell中调用某些内容,请使用以下命令:

>>> import os
>>> os.system('echo hello')
hello
0
>>> 

>>> import subprocess
>>> subprocess.call(['echo', 'hello'])
hello
0
>>> 

如果要使用ls之类的命令,请使用以下代码:

>>> import os
>>> x = os.popen('ls ~/Desktop').read().split()
>>> x
['...
']

我认为这就是您的意思,但如果您可以在问题中添加更多详细信息,那就太棒了。

答案 2 :(得分:0)

使用Popen构造函数在python中调用shell命令。 看看这个answer

另外,这是另一个代码:

   from subprocess import Popen, PIPE

    output = Popen(['ls -l'], stdout=PIPE, stderr=PIPE, shell=True)
    (out,err) = output.communicate()

out包含来自ls -l的标准输出 和err包含来自ls -l <​​/ p>的stderr