Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python使用sort命令?_Python_Sorting_Command_Subprocess - Fatal编程技术网

如何使用python使用sort命令?

如何使用python使用sort命令?,python,sorting,command,subprocess,Python,Sorting,Command,Subprocess,我有一堆不同的文本文件,我正试图把这些文本整理成一个文件。我正在使用python的子流程,并编写了以下代码 command_line = "sort -m 1.txt 2.txt > a.txt" args = shlex.split(command_line) subprocess.call(args) 结果,subprocess.call(args)返回2,在a.txt中没有写入任何内容。我的代码有问题吗?如果要在命令行中使用shell重定向操作符,必须将shell=True传递给子

我有一堆不同的文本文件,我正试图把这些文本整理成一个文件。我正在使用python的子流程,并编写了以下代码

command_line = "sort -m 1.txt 2.txt > a.txt"
args = shlex.split(command_line)
subprocess.call(args)

结果,subprocess.call(args)返回2,在a.txt中没有写入任何内容。我的代码有问题吗?

如果要在命令行中使用shell重定向操作符
,必须将
shell=True
传递给
子进程。调用
。否则,“>”和“a.txt”将作为命令行参数传递给
sort
。使用
shell=True
,命令行被传递给实际的shell并由其解释,因此您不应该
shlex.split
它。使用
os.system
比使用默认使用shell的
subprocess.call
更容易。

不相关:
sort-m
不会对文件进行排序。它合并已排序的文件。另请参阅“必须”有点强<代码>调用('sort-m1.txt 2.txt'.split(),stdout=open('a.out','w'))
在没有
shell=True的情况下工作。如果要使用实际的shell命令行,请参阅重复问题的答案。我会澄清答案。