您可以从另一个编辑.py脚本吗?

时间:2019-08-05 05:37:53

标签: python

我正在创建一个计算图像的欧几里得距离的相似度程序,我在寻找用户输入,以便如果他们想使用部分代码,他们可以选择。在这种情况下,需要将一行(在dc2.py中具体为13)更改为“”。我该怎么办?

我尝试在.write旁边使用open函数,通过open(dc.py).read()打开文件,但无济于事。

这会将图像转换为数组(程序dc2.py):

import numpy as np
import imageio
from numpy import array


img = imageio.imread("Machine Screw.jpg")
data = array(img)

with open('test2.txt', 'w') as outfile:

        np.savetxt(outfile, data_slice, fmt='%-7.2f')

exec(open("Halfer.py").read())

以下是更改以前的.py的代码:

inp = input("Want to use halfer?: ")

if inp == 'y':
    the_file = open('dc2.py', 'a')
    the_file[13].write(' ')

--------------------------------------

我期望:

进程结束,退出代码为0


这是实际发生的事情:

Traceback (most recent call last):
  File "C:/Users/User/Desktop/PySimCode/Resources/Ini.py", line 5, in <module>
    the_file[13].write(' ')
TypeError: '_io.TextIOWrapper' object is not subscriptable

谢谢您的帮助!

3 个答案:

答案 0 :(得分:1)

您要实现的解决方案不太“ Pythonic”。我认为您应该将dc2.py文件作为模块导入Ini.py脚本,并使用基于用户输入的参数来操纵dc2.py脚本的行为。

例如:

dc2.py

import numpy as np
import imageio
import subprocess
from numpy import array


def image_converter(halfer_needed=True):
    img = imageio.imread("Machine Screw.jpg")
    data = array(img)

    with open('test2.txt', 'w') as outfile:

        np.savetxt(outfile, data, fmt='%-7.2f')

    if halfer_needed:
        sp = subprocess.Popen(["python", "Halfer.py"])  # Call Halfer.py script
        ret_stdout, ret_stderr = sp.communicate()  # These variables contain the STDOUT and STDERR
        ret_retcode = sp.returncode  # This variable conains the return code of your command

我认为如果用户需要,您想调用Halfer.py脚本,因此,如上所示,我已使用子进程模块来调用此脚本。您可以查看有关此模块的更多详细信息和选项:https://docs.python.org/3/library/subprocess.html

Ini.py

from dc2 import image_converter  # Import your function from "dc2.py" script 

inp = str(input("Want to use halfer?: "))

if inp == 'y':
    image_converter(halfer_needed=False)
image_converter()  # you don't need to define the keyword argument because the default value is True.

答案 1 :(得分:1)

尝试一下:

inp = raw_input("Want to use halfer?: ")

if inp == 'y':
    origin_file = open('dc2.py','r').readlines()
    the_file = open('dc2.py','w')
    origin_file[12] = '\n'
    for line in origin_file:
        the_file.write(line)
    the_file.close()

一些我想补充的笔记:

  1. input读取一段文本并进行分析。您可能应该始终使用raw_input
  2. open执行不同的操作,具体取决于 mode 参数。就我而言,我使用r进行阅读,然后使用w进行写作。 (我不认为可以在同一<open>对象上进行读写)。 a被追加,仅允许您添加行。阅读here
  3. 要从<open>获取内容,请使用.read().readlines()
  4. 第13行是索引12。此外,我将其更改为'\n',而不是' '
  5. 完成操作后,别忘了在您的.close()上致电<open>

希望这对您有用!

答案 2 :(得分:1)

可以,但是不可以。

您正在尝试基于um imput激活一些代码,这可以将代码封装在函数中,您可以根据条件导入和删节。 您正在尝试通过读取文件并手动执行文件来获得此结果,基本上,您正在执行Python解释器应该执行的操作。

首先,您需要将模块更改为可随意激活的内容,而不是在文件加载后立即激活,例如dc2.py如下所示:

import numpy as np
import imageio
from numpy import array

import Halfer  # <- here you import the py file, not open and read

def run(use_halfer):
    img = imageio.imread("Machine Screw.jpg")
    data = array(img)

    with open('test2.txt', 'w') as outfile:
        np.savetxt(outfile, data_slice, fmt='%-7.2f')

    if use_halfer:
        Halfer.run()

..和Halfer.py文件应如下所示:

def run():
    # ..all your Halfer.py code here inside the run function

..然后脚本的起点看起来像:

import dc2
inp = input("Want to use halfer?: ")

dc2.run(inp == 'y')  # <- here you tell dc2 to use halfer or not.
相关问题