我正在使用此代码从外部程序获取标准输出:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
communic()方法返回一个字节数组:
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)
但是,我想将输出作为普通的Python字符串.所以我可以这样打印:
>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
Run Code Online (Sandbox Code Playgroud)
我认为这是binascii.b2a_qp()方法的用途,但是当我尝试它时,我又得到了相同的字节数组:
>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)
有人知道如何将字节值转换回字符串吗?我的意思是,使用"电池"而不是手动操作.而且我希望它能用于Python 3.
我有一个python模块,其中包含各种数据文件(代表曲线的一组csv文件),需要在运行时加载。csv模块效果很好
# curvefile = "ntc.10k.csv"
raw = csv.reader(open(curvefile, 'rb'), delimiter=',')
Run Code Online (Sandbox Code Playgroud)
但是,如果我将此模块导入另一个脚本,则需要找到数据文件的完整路径。
/project
/shared
curve.py
ntc.10k.csv
ntc.2k5.csv
/apps
script.py
Run Code Online (Sandbox Code Playgroud)
我希望script.py仅按基本文件名而不是完整路径来引用曲线。在模块代码中,我可以使用:
pkgutil.get_data("curve", "ntc.10k.csv")
Run Code Online (Sandbox Code Playgroud)
可以很好地找到文件,但是它返回已读入的csv文件,而csv.reader需要文件句柄本身。有什么方法可以使这两个模块一起正常工作?它们都是标准的库模块,因此我并不是真的期望出现问题。我知道我可以开始拆分pkgutil二进制文件数据,但是那样的话我也可能不使用csv库。
我知道我可以只在模块代码中使用它,而不必理会pkgutils,但看起来pkgutils确实正是此目的。
this_dir, this_filename = os.path.split(__file__)
DATA_PATH = os.path.join(this_dir, curvefile)
raw = csv.reader(open(DATA_PATH, "rb"))
Run Code Online (Sandbox Code Playgroud)