简体   繁体   English

Python代码可交互运行,但不能作为脚本运行

[英]Python code runs interactively but not when run as script

I am new to python and have looked at similar questions but none seems to offer a solution to my simple case so I suspect I have made a basic error. 我是python新手,也曾研究过类似的问题,但似乎没有一个解决方案可以解决我的简单情况,因此我怀疑我犯了一个基本错误。 I am using Python 2.7 on a Mac and on Ubuntu running on a Chromebook. 我在Mac和在Chromebook上运行的Ubuntu上使用Python 2.7。 When the project is complete I shall transfer it to a Raspberry Pi. 项目完成后,我将其转移到Raspberry Pi。

This snippet of code runs without a problem if I invoke the interpreter with the python call and type in the code. 如果我使用python调用调用解释器并键入代码,则此代码段运行不会出现问题。

switch = (int(time.strftime("%M"))%2
WhichOne = "Right","Left"
usbname = WhichOne[switch]

However, when I run the script containing this code fragment by typing ./project20160218.py or python project20160218.py 但是,当我通过输入./project20160218.py或python project20160218.py运行包含此代码片段的脚本时

I obtain 我得到

 user@chrubuntu:~/Documents/Degree day project$ python project20160218.py
  File "project20160218.py", line 23
  WhichOne = "Right","Left"
       ^
  SyntaxError: invalid syntax

I would be very grateful for some guidance here. 我非常感谢这里的一些指导。

Thanks. 谢谢。

You're missing a closing parenthesis in the first line just before %2: 您在%2之前的第一行中缺少右括号:

switch = (int(time.strftime("%M")))%2
WhichOne = "Right","Left"
usbname = WhichOne[switch]

If you close that it works. 如果关闭,它会起作用。 Also I assume you're importing time elsewhere, otherwise that would be undefined and also cause issues. 我还假设您要将时间导入其他地方,否则将无法定义时间,并且还会导致问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 像运行交互式脚本一样运行python脚本 - Run python script as if it was run interactively 检测何时在 ipython 中以交互方式运行 python 脚本 - Detecting when a python script is being run interactively in ipython 如何在网页上以交互方式运行 python 或 bash 脚本? - How to run a python or bash script interactively on a webpage? 以交互方式/非交互方​​式运行时,Python以不同方式导入模块 - Python importing modules differently when run interactively/non-interactively Pynotify可以很好地交互运行,但是以编程方式运行时会崩溃(在Fedora 13上) - Pynotify runs fine interactively, but crashes when run programmatically (on Fedora 13) 代码显示以交互方式运行时的结果,而不是从外壳运行时显示的结果 - Code shows results when run interactively, but not when run from a shell 如何从python脚本交互式运行其他程序 - How to run some other program interactively from a python script Python 脚本在 anaconda3 上运行时无法在 cmd 上运行 - Python script doesn't run on cmd when it runs on anaconda3 当代码在 Python 中运行时,交互式 Window 运行缓慢 - Interactive Window Runs Slow Constantly When Code Run in Python Interactive python脚本在x秒后运行,但插入tkinter代码时它只运行一次 - python script runs after x seconds but when tkinter code inserted it runs only once
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM