如何导入而不使用" import"在python中

时间:2017-06-20 15:36:19

标签: python python-3.x module subprocess python-2.x

这个问题的背景是我正在尝试编写一个程序来协助分析数据。它应该用python3编写,但是它的数据类型通常以python无法读取的格式存储。 有一个包来读取这些数据,但它只与python2兼容。为了读取数据,我因此想要编写一个python2脚本来读取文件并将其转换为numpy数组。我想在我的python3程序中阅读。 (有问题的包是axographio 1)。

一般来说,我想要的是:

给出像

这样的(python2)脚本
#reading.py
import numpy
x = numpy.random.random(size=10000)

运行一个(python3),它可以以某种方式得到x

#analyze.py
import matplotlib.pyplot as plt
#fancyfunction that gets x from reading.py
plt.plot(x)
plt.show()

这里重要的是read.py由python2解释器执行,因为它不能用于python3。

2 个答案:

答案 0 :(得分:6)

您是否尝试过挑选数据

在python 2中

import pickle
pickle.dumps(x)

在python 3中

import pickle
pickle.load(x)

如果我没记错的话,更好的方法是将你的numpy数组保存在python 2中的json文件中(可能使用panda over numpy),并在python 3中执行相反的操作

类似的东西:

df = pandas.Data[...]

有关详细信息,请参阅http://www.thegeeklegacy.com/t/how-to-import-without-using-import-in-python/35/#post-103

答案 1 :(得分:0)

以下是我使用的解决方案。 从subprocess模块我使用带有参数Popen的函数shell=True从python3调用我的python2脚本并收集stdout。 (这意味着所有内容都已打印到控制台。)

这是我想在python3中调用的python2代码:

#readying.py
import axographio #this is the python2 package
import os #specific to the problem of reading data
import sys #needed to use arguments from the command line
if __name__=='__main__': #when y
    path = sys.argv[1]
    filename = sys.argv[2]
    os.chdir(path)
    file = axographio.read(filename)
    # print 'done reading files'

    data = file.data

    no_measurements = len(data)
    measurement_len = len(data[0])

    print(no_measurements)
    print(measurement_len)
    for i, name in enumerate(file.names):
        print(name)
    for i in range(no_measurements):
        for j in range(measurement_len):
            print(data[i][j])
        print('next measurement') 
       #this acts as a seperator when reading the data in python3, anything that cannot be converted to a float works

这段代码的作用只是从commad行中获取参数。 (使用sys模块,可以使用python2 script.py arg1 arg2 arg2形式将命令行中的.py脚本传递给它们。 使用print语句给出reading.py的输出。请注意,我单独打印每个数据,以避免截断输出。通过这种方式,输出是stdout调用的标准输出python2

python3代码是

#analyze.py
import subprocess
import numpy as np

def read_data(path, filename):
    module_name = 'reading.py'
    cmd = 'python2 '+module_name+' '+path+' '+filename
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    out, err = p.communicate()
    #out is a bytes object

    result = out.split(b'\n') #the output from different print statements is seperated by "b'\n'" in the bytes object


    #everything below here is concerned with unpacking the output and structuring it as I needed it         
    output = []
    i = 0
    while i < len(result):
        output.append(result[i].decode("utf-8"))
        i+=1
    ind = 0 #this should keep track of where in the output list we are
    no_measurements = int(output[ind])
    ind += 1
    measurement_len = int(output[ind])
    ind += 1

    names = []
    for i in np.arange(ind,ind+no_measurements):
        names.append(output[i])
        ind += 1

    data = []
    measurement = []
    while ind<len(output):
        try:
            measurement.append(float(output[ind]))
            ind+=1
        except:
            data.append(measurement)
            measurement = []
            ind+=1
    data = np.array(data)

    return names, data

这样做是使用subprocess模块作为shell命令python2 reading.py path filename执行。如上所述,此调用的stdout是其print语句的输出。这些是用{UTF-8'编码的bytes个对象。使用decode方法,可以将它们转换为字符串对象,然后可以使用float等函数更改类型。 (这是为什么单独打印所有内容非常有用的另一个原因,因为必须扫描字符串以查找数组或数字是相当烦人的。)在readying.py中,数据在打印时明显分开,这使得它很容易一旦他们被阅读就构建它们。

标签:python3中的axographio - 读取axograph文件python3

相关问题