将多行代码转换为一行

时间:2018-11-06 13:49:24

标签: python

我想将以下代码放在一行中:

from sys import argv
script,from_file,to_file = argv
print(f"copying from {from_file} to {to_file}")
in_file = open(from_file)
indata = in_file.read()
input("move one == enter")
out_file = open.(to_file,'w')
out_file.write(indata)
out_file.close()
in_filen.close()

这可能吗?

我认为与;在一起,但我不记得了。

2 个答案:

答案 0 :(得分:1)

阅读docs

  

一个简单的语句包含在单个逻辑行中。一些   简单的语句可能在用分号分隔的一行上出现。

搜索堆栈溢出! How to put multiple statements in one line?

或者通过Google查找更复杂程序的转换器:https://onelinepy.herokuapp.com/

答案 1 :(得分:0)

您的代码的单行版本最终可能如下所示:

exec("""\nfrom sys import argv\nscript,from_file,to_file = argv\nprint(f"copying from {from_file} to {to_file}")\nin_file = open(from_file)\nindata = in_file.read()\ninput("move one == enter")\nout_file = open(to_file,'w')\nout_file.write(indata)\nout_file.close()\nin_filen.close()\n""")

或者这个:

(lambda __g, __print: (lambda __mod: [[(__print('copying from {from_file} to {to_file}'), [[(input('move one == enter'), [(out_file.write(indata), (out_file.close(), (in_filen.close(), None)[1])[1])[1] for __g['out_file'] in [(open(to_file, 'w'))]][0])[1] for __g['indata'] in [(in_file.read())]][0] for __g['in_file'] in [(open(from_file))]][0])[1] for (__g['script'], __g['from_file'], __g['to_file']) in [(argv)]][0] for __g['argv'] in [(__mod.argv)]][0])(__import__('sys', __g, __g, ('argv',), 0)))(globals(), __import__('__builtin__', level=0).__dict__['print'])

第一种方式是直观的。第二种方法留作练习,以弄清楚那里发生了什么。网上有很多在线工具可以将您的多行 Python 转换为单行。


简单工具

当我需要在远程系统上单行代码化和运行 Python 时,我使用了一种简单的技术。

# Howdy
def main():
    print("Hello,")
    print("World")
    # That was fun!

if __name__ == "__main__" or True:

    # BEGIN #
    import pipes
    import re
    with open(__file__) as f:
        contents = f.read()
        regex = r"^(.+?)#\sBEGIN\s#.+?#\sEND\s#(.+)$"
        core = re.sub(regex, "\\1\\2", contents, 0, re.MULTILINE | re.DOTALL)
        escaped = f"{core!r}"
        outer = pipes.quote(f"exec({escaped})")
        oneline = f"python -c {outer}"
        print(oneline)
    # END #

    main()

输出:

python -c 'exec('"'"'# Howdy\ndef main():\n    print("Hello,")\n    print("World")\n    # That was fun!\n\nif __name__ == "__main__" or True:\n\n    \n\n    main()\n'"'"')'
Hello,
World

一行代码是这样的:

python -c 'exec('"'"'# Howdy\ndef main():\n    print("Hello,")\n    print("World")\n    # That was fun!\n\nif __name__ == "__main__" or True:\n\n    \n\n    main()\n'"'"')'

说明

该工具被拼写出来,所以很容易理解,但关键的是底部的代码读取当前文件的全部内容,从自身中删除工具代码,转义换行符和引号,然后将其全部包装在 { {1}} - 非常元!

哦,exec 只是因为我喜欢在 PyCharm 中运行我的脚本,并在装订线中使用有用的播放按钮。随意省略这一点。


OP 的具体案例

if __name__ == "__main__" or True:

运行上述(并注意我为解释 def main(): from sys import argv _, script, from_file, to_file = argv print(f"copying from {from_file} to {to_file}") in_file = open(from_file) indata = in_file.read() input("move one == enter") out_file = open(to_file,'w') out_file.write(indata) out_file.close() in_file.close() if __name__ == "__main__" or True: # BEGIN # import pipes import re with open(__file__) as f: contents = f.read() regex = r"^(.+?)#\sBEGIN\s#.+?#\sEND\s#(.+)$" core = re.sub(regex, "\\1\\2", contents, 0, re.MULTILINE | re.DOTALL) escaped = f"{core!r}" outer = pipes.quote(f"exec({escaped})") oneline = f"python3 -c {outer}" print(oneline) # END # main() 而做出的 argv 转变),这是您的单行:

-c

然后运行上面的命令并将三个参数添加到该命令的末尾,就好像它是一个文件一样。哈。