使用调用shell命令操作系统

2024-04-16 20:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用os.system调用外部(管道)shell命令:

srcFile = os.path.abspath(sys.argv[1])

srcFileIdCmd = "echo -n '%s' | cksum | cut -d' ' -f1" % srcFile

print "ID command: %s" % srcFileIdCmd

srcFileID = os.system(srcFileIdCmd)

print "File ID: %s" % srcFileID

输出

ID command: echo -n '/my/path/filename' | cksum | cut -d' ' -f1
File ID: 0

但当我跑的时候

echo -n '/my/path/filename' | cksum | cut -d' ' -f1

在命令行上手动获取2379496500,而不是0。你知道吗

要从shell命令中获得正确的值,我需要更改什么?你知道吗


Tags: path命令echoidosshellsystemcommand
1条回答
网友
1楼 · 发布于 2024-04-16 20:22:12

使用

sp = subprocess.Popen(["program", "arg"], stdout=subprocess.PIPE)

相反,然后从文件sp.stdout中读取。所讨论的pogram可以是shell,您可以将复杂的shell命令作为参数(["/usr/bin/bash", "-c", "my-complex-command"])传递给它。你知道吗

相关问题 更多 >