Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/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 2.7 Python-Can';t读取文件-子进程_Python 2.7 - Fatal编程技术网

Python 2.7 Python-Can';t读取文件-子进程

Python 2.7 Python-Can';t读取文件-子进程,python-2.7,Python 2.7,我的小脚本选择重命名一些文件 有一个明确的结局。为此,我读取了文件名 然后要用正则表达式编辑字符串 我现在的问题是,奇怪的是,当我打开创建的文件时 出于阅读目的,我看不懂其中的台词。 当我在pythons交互式shell中运行这些行时,它就工作了 """ Small script to rename music files """ import subprocess import re subprocess.call(["touch","temp.txt"]) with open('

我的小脚本选择重命名一些文件 有一个明确的结局。为此,我读取了文件名 然后要用正则表达式编辑字符串

我现在的问题是,奇怪的是,当我打开创建的文件时 出于阅读目的,我看不懂其中的台词。 当我在pythons交互式shell中运行这些行时,它就工作了

"""
Small script to rename music files
"""


import subprocess
import re



subprocess.call(["touch","temp.txt"])

with open('temp.txt','w') as myfile:
    myfile = open('temp.txt','w')
    p = subprocess.Popen(["ls"],stdout=myfile,stderr=subprocess.STDOUT,shell = False    )



with open('temp.txt','r') as file_1:
    text = file_1.readlines()
我的猜测是,这个问题与 子流程的方法Popen。但对我来说这是一个巨大的黑盒子 我只是从别的地方抄来的


问候

我想这是一个竞争条件,因为使用
Popen
创建的子进程是异步运行的。添加一个
p.communicate()
(等待子进程终止)将解决问题,但事实上,在您的情况下,
子进程.call
就足够了。谢谢,一切正常。有趣的是,我第一次想使用subprocess调用,但它不起作用,因为我不知道您可以将输出更改为选项,所以我改为在stackoverflow上找到的脚本中使用的popen。无论如何,谢谢你,我学到了一些新东西:)